componentDidMount equivalent on a React function/Hooks component?

jeyko picture jeyko · Dec 27, 2018 · Viewed 32.8k times · Source

Are there ways to simulate componentDidMount in React functional components via hooks?

Answer

Mertcan Diken picture Mertcan Diken · Feb 12, 2019

For the stable version of hooks (React Version 16.8.0+)

For componentDidMount

useEffect(() => {
  // Your code here
}, []);

For componentDidUpdate

useEffect(() => {
  // Your code here
}, [yourDependency]);

For componentWillUnmount

useEffect(() => {
  // componentWillUnmount
  return () => {
     // Your code here
  }
}, [yourDependency]);

So in this situation, you need to pass your dependency into this array. Let's assume you have a state like this

const [count, setCount] = useState(0);

And whenever count increases you want to re-render your function component. Then your useEffect should look like this

useEffect(() => {
  // <div>{count}</div>
}, [count]);

This way whenever your count updates your component will re-render. Hopefully this will help a bit.