How useEffect hook works in React?

Maneet Lodha
2 min readDec 2, 2020

In my last blog post, I talked about useReducer hook in react. Here, I want to talk about useEffect which is one of the most used hook in react. It makes the rendering of side effects so much easy whenever there is a change in state or while mounting or unmounting component.

The useEffect hok was designed to simplify the process of creating side effects in class-based components. The simple way to create useEffect hook is to pass a function that contains the side effect which you need to run when the component first mounted or state is changed but it is not the case all time so it also takes a second optional parameter which contains an array. In this array, you can pass a variable, state, or object. The useeffect will run whenever there will be a change in the value of the array. We can also add the clean-up the to previous effect in the same hook. This can be done by adding a return statement which will run before the main logic, this will happen only if the useeffect has at least run once.

I recently made a project using this hook which is a simple Todo app using local storage. You can call the useeffect hook to load all the todos whenever there is a new todo added and also use another useeffect when a todo is completed and removed from local storage. You can find the project source code at https://github.com/maneetlodha28/todoWithLocalStorage.

Overall, useeffect simplifies side effects in components much easier by running them whenever there is a change in a state or props.

--

--