DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 21

The task is to implement a useUpdateEffect hook that works the same as the useEffect, except that it skips running the callback on first render.

The boilerplate code:

import React, {EffectCallback, DependencyList} from 'react';

export function useUpdateEffect(effect: EffectCallback, deps?: DependencyList) {
  // your code here
}


// to try your code on the right panel
// export App() component like below

// export function App() {
//   ...
//   return <div>BFE.dev</div>
// }

Enter fullscreen mode Exit fullscreen mode

A ref to check if it is the first render is the first thing to do.

const firstRender = useRef(true)
Enter fullscreen mode Exit fullscreen mode

The default state is true, and subsequently, firstRender is set to false. To skip the callback on first render:

useEffect(() => {
  if(firstRender.current) {
   firstRender.current = false;
   return;
}
 return effect();
}, deps)
Enter fullscreen mode Exit fullscreen mode

The complete code looks like this:


import React, {useRef, useEffect, EffectCallback, DependencyList} from 'react';

export function useUpdateEffect(effect: EffectCallback, deps?: DependencyList) {
  // your code here
  const firstRender = useRef(true);

  useEffect(() => {
    if(firstRender.current) {
      firstRender.current = false
      return;
    }
    return effect()
  }, deps)
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)