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>
// }
A ref to check if it is the first render is the first thing to do.
const firstRender = useRef(true)
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)
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)
}
That's all folks!
Top comments (0)