How to use componentWillUpdate in functional component by react hooks?
Asked Answered
S

3

8

How to use componentWillUpdate in functional component by react hooks ?

Sivan answered 16/11, 2019 at 13:6 Comment(0)
E
1

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*/
      
  });
Ermentrude answered 16/11, 2019 at 13:42 Comment(2)
but here still it runs after the render. not before it.Tensiometer
@Tensiometer you are right, the above solution is for the componentDidUpdate.Chainsmoke
U
1

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.

Unsearchable answered 20/12, 2022 at 19:37 Comment(0)
R
-2
// similar to componentWillUpdate
useMemo(()=>{
    doSomething() 
}, [dep1, dep2])
Rustler answered 14/12, 2022 at 5:13 Comment(1)
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 WillStorz

© 2022 - 2024 — McMap. All rights reserved.