When does React's useEffect get triggered during component lifecycle?

Viewed 1369

I don't quite understand what "Mount" means in React and when useEffect and clean up function are triggered.

In the example below. It appears that the useToggle hook is "bonded" (the correct term?) to the App component, and every time variable isOn gets updated, the bonded App component gets re-rendered. However, the cleanup function gets called as well. I tried to compare it to React's class component's life cycle.

Correct me if my understanding is wrong.

Reference: Diagram from Trey Huffine with edits

useEffect(updateFunc => cleanupFunc, [dependency array]) on Life Cycle enter image description here

const { useReducer, useEffect } = React;

// Purposefully moved the toggle logic to a custom hook for understanding
function useToggle(inital) {
  const [isOn, toggle] = useReducer(isOn => !isOn, inital);
  useEffect(()=>{
    console.log("update function called");
    return () => console.log("cleanup function called");
  }, [isOn])
  return [isOn, toggle];
}

function App() {
  const [isOn, toggle] = useToggle(false);
  return (
    <div>
      <input type='checkbox' value={isOn} onClick={toggle}/> 
      Click Me
    </div>
  )
}

ReactDOM.render(<App/>, document.querySelector('.App'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div class='App'/>

2 Answers

Mounting means when a component is just added to the DOM. In a class component, it's one of the next calls after the constructor is called.

In functional components we don't really have an onMount event, rather we have the useEffect hook.

useEffect has some differences from componentDidMount, the latter is only called once (onMount), while the former is called every time a component gets re-rendered. A component is re-rendered whenever the state/props change.

From React docs:

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

Since useEffect can be called multiple times, it also has to cleanup multiple times:

When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.

After loading the basic data use Effect is rendered

Which mean that if your page got data loading from an api. If we assume data is an array.

First the react component will render empty array [ ]. after that useeffect hook will load the data & render the html again with loaded data

use effect is function is like componentDidMount + componentDidUpdate + componentwillUpdate + componentwillUnmount

If condition is not specified useeffect hook will render every update.

basic useeffect

useEffect(() => {
  //Write the effect
  return () => {
    cleanup
  }
//specific condition to be triggered if you have one
}, [condition])

You can have multiple useEffect inside a function component. If you don't want all useeffect hook do be called every update. If you specified the condition.

Will be called when conditionOne is changed

useEffect(() => {
      //Write the effect
      return () => {
        cleanup
      }
    //specific condition to be triggered if you have one
    }, [conditionOne])

Will be called when conditionTwo is changed

useEffect(() => {
      //Write the effect
      return () => {
        cleanup
      }
    //specific condition to be triggered if you have one
    }, [conditionTwo])

In most cases the condition is refer to the state

Related