How to use componentWillUpdate in functional component by react hooks ?
You can create the same effect of componentWillUpdate using the combination of refs and effect hooks.
Docs says componentWillUpdate,is called every time when update,occurs.It is not called on initial render.
Now using useRef hook,the returend object is persited in the complete life time of the application.
const isFirstRender = React.useRef(true);
React.useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}
/*business logic for component did update*/
});
You can achieve similar behaviour using useLayoutEffect
which will run first before all your useEffects
* and before rendering your elements on screen. Therefore, if you have used useLayoutEffect
on for example animations to prepare "visual" before rendering it to the user (which was the primary use of it) it should do the trick.
useLayoutEffect(() => {
// do some modifications before rendering my component
}, [props])
*This is because useLayoutEffect is fired synchronously after DOM is mutated and before the browser paints the new changes.
// similar to componentWillUpdate
useMemo(()=>{
doSomething()
}, [dep1, dep2])
useMemo
is used for 1. Memoizing result
of super slow function for same inputs 2. Solving Referential equality problems
in dependencies re-triggering. Besides the memoization it acts the same way UseEffect does which would be componentDidMount
/ componentDidUpdate
but not Will
–
Storz © 2022 - 2024 — McMap. All rights reserved.