State Management in Pure React with Hooks: useEffect

Bipin Rajbhar - Apr 10 '20 - - Dev Community

Hello, everyone πŸ‘‹, I hope you are doing great 😊.

So, today you are going to learn all the fundamental concepts of useReducer() Hook in this article.

Before you start, there are some rules you need to follow to use Hooks 😟. Thankfully the React Team has provided an ESLint Plugin called eslint-plugin-react-hooks that will help enforce these rules when using Hooks 🀩.

useEffect Hook

The useEffect() Hook allows you to perform side effects in the functional component. The side effects could be data fetching, setting up a subscription, and manually changing the DOM to React components.

The useEffect() Hook takes two arguments. The first argument is a function in which you can perform your side effects, and the second argument is an array of variables (optional).

If you do not provide the second argument, then the useEffect() Hook runs after every render.

Example

If you have noticed, the example given above behave similarly as componentDidUpdate()

If you provide an empty array in the second argument, then the useEffect() Hook run only one time.

Example

If you have noticed, the example given above behave similarly as componentDidMount()

If you provide an array with a variable in the second argument, then the useEffect() Hook run only when the variable change.

Example

If you have noticed, the example given above behave similarly as componentDidUpdate()

Before we end this article, I want to mention that you can also mimic the behavior of componentDidUnmount() by simply returning a function.

Example

If you are family with React class lifecycle methods, you can think of useEffect() Hook as componentDidMount(), componentDidUpdate() and componentDidUnMount() combined.

Now, you have learned all the fundamental concepts of useReducer() Hook 🀘.

Thanks for reading! My name is Bipin Rajbhar; I love helping people to learn new skills 😊. You can follow me on Twitter if you’d like to be notified about new articles and resources.

. . . . . . . . . . . . . . . . . . . . . . . . .