How to use componentWillUpdate in functional component by react hooks ?
3 Answers
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*/
});

- 339
- 2
- 7
-
8but here still it runs after the render. not before it. – hasan Feb 04 '21 at 09:35
-
2@hasan you are right, the above solution is for the componentDidUpdate. – Ashish Rawat Jun 11 '21 at 06:41
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.

- 3,256
- 1
- 18
- 25
// similar to componentWillUpdate
useMemo(()=>{
doSomething()
}, [dep1, dep2])

- 2,856
- 7
- 21
- 41

- 11
- 3
-
`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` – Sebastian Voráč MSc. Dec 20 '22 at 19:44