DEV Community

Discussion on: React Component Lifecycle

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

If I may, I'd like to add documentation using react hooks:

Initialisation will be the base state of your component before it fetches data and/or sets some states etc. The rest can be reduced to a single hook: useEffect as follows:

useEffect(() => {
  console.log("mount & update");

  return () => {
    console.log("cleanup / will unmount");
  };
}, [dependencies?]);
Enter fullscreen mode Exit fullscreen mode

If you set dependencies it will act as update. Without dependencies (empty array) it will execute only on mount life-cycle step. Then

MOUNT

useEffect(() => {
  console.log("mount");
}, []);
Enter fullscreen mode Exit fullscreen mode

This is a perfectly valid code. You can set a hook without unmounting (return) or dependencies.
Also, you can set multiple useEffect hooks for a single component.

UPDATE:

useEffect(() => {
  console.log("update");
}, [myState]);
Enter fullscreen mode Exit fullscreen mode

The useEffect hook will trigger each time "myState" gets changed.

UNMOUNT

componentWillUnmount is used for cleanup (like removing event listeners, cancel the timer etc). Say you are adding a event listener in componentDidMount and removing it in componentWillUnmount as below.

componentDidMount() {
  window.addEventListener('mousemove', () => {})
}

componentWillUnmount() {
  window.removeEventListener('mousemove', () => {})
}
Enter fullscreen mode Exit fullscreen mode

Hook equivalent of above code will look as follows

useEffect(() => {
  window.addEventListener('mousemove', () => {});

  // returned function will be called on component unmount 
  return () => {
    window.removeEventListener('mousemove', () => {})
  }
}, [])
Enter fullscreen mode Exit fullscreen mode

All custom hooks will then use useEffect hook to be defined. You can see examples of custom hooks here .
* Sometimes the ones showed on that site can be optimised either be for performance of for readability.

You can find the complete hooks API here .

Hope it helps somehow 👌😁

Collapse
 
sylwiavargas profile image
Sylwia Vargas

Just popping in here to say that we are rewriting the useEffects section of the docs as well as the API reference - stay tuned!