How to replace React lifecycle methods with React Hooks in functional components? First, let’s see to lifecycle methods diagram.

Image for post

You don’t need the constructor method in functional components. Use the [useState](https://reactjs.org/docs/hooks-state.html)Hook to initialize the state.

The common React component lifecycle methods arecomponentDidMount,``componentDidUpdate and componentWillUnmount. For all cases we should use the [useEffect](https://reactjs.org/docs/hooks-effect.html)Hook. Let’s see an example for details.

//componentDidMount and componentDidUpdate. An effect re-runs every render

	useEffect(() => {
	    // to do smth...
	})

	//componentDidMount. An effect runs only on mount

	useEffect(() => {
	    // to do smth...
	}, [])
view raw
demo.tsx hosted with ❤ by GitHub

For componentWillUnmount method, we should add the return statement to the useEffect Hook.

useEffect(() => {
	  // to do smth...

	  return () => {
	    // to do smth else when a component is unmounted...
	  }
	})
view raw
demo.tsx hosted with ❤ by GitHub

#react-lifecycle #react #react-hook

Using React Hooks instead of lifecycle methods
2.85 GEEK