How to use componentWillUpdate in functional component by react hooks?

DIXIT Kumar picture DIXIT Kumar · Nov 16, 2019 · Viewed 8.9k times · Source

How to use componentWillUpdate in functional component by react hooks ?

Answer

Atishay Baid picture Atishay Baid · Nov 16, 2019

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*/
      
  });