<aside> 💡 Original Post by *Trent Yang* - Rights, Credits and Kudos for him

</aside>

Replace lifecycle with hooks in React

If you have ever used React, you should be familiar with power of React lifecycles. The upcoming React hooks are about to change the way we handle lifecycles.

React hooks are a unification of existing features including state and lifecycles. In this post I am going to show you how to convert lifecycle class methods into React hooks to shine some light on React hooks.

For each of the three most common lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount), I will demonstrate a class style implementation and a hooks style counterpart followed by an explanation.

componentDidMount

class Example extends React.Component { 
  componentDidMount() { 
    console.log('I am mounted!'); 
  } render() { 
    return null; 
  }
}
function Example() { 
  useEffect(() => 
    console.log('mounted')
  , []);
  return null;
}

useEffect is a React hook where you can apply side effects, for example, getting data from server.

The first argument is a callback that will be fired after browser layout and paint. Therefore it does not block the painting process of the browser.

The second argument is an array of values (usually props).

componentDidUpdate

componentDidMount()  { console.log('mounted or updated'); }
componentDidUpdate() { console.log('mounted or updated'); }
useEffect(() => console.log('mounted or updated'));

There is not a straight forward implementation in hooks to replace componentDidUpdate. The useEffect function can be used to trigger callbacks after every render of the component including after component mounts and component updates.

However this is not a big problem since most of the time we place similar functions in componentDidMount and componentDidUpdate.