Dependency array in useEffect hook

The value passed matters more than you think

Shreejit Rajbanshi
Devil is in the Details
2 min readMay 9, 2022

--

React hooks have simplified how we write code. The useEffect hook alongside useState, helps functional component handle states, removing the need for class components.

Understanding useEffect hook will help us avoid bugs, that might keep our head scratching for hours.

Photo by Nick Fewings on Unsplash

Dependency Array

One of the arguments that the useEffect accepts, after the callback function is the dependency array. This array defines the list of variables that if changed will trigger the callback function.

Let us take a look at some of the parameters that can be passed in place of the dependency array, and how it affects the hook itself.

1. Skipping the argument:

We may skip passing the second argument. If we choose to do so then our hook will trigger the callback function on each re-render of the component. Any unrelated state change will trigger the callback function to execute inducing bugs, and compromising performance.

2. Empty Array ( [] )

An empty array simply means that there are no dependencies that will trigger the callback within it. Our code inside the callback will run once when the component gets registered, and that is it. The useEffect hook acts like componentDidMount method if an empty array is passed as the dependency array.

3. Array of dependencies ( [variable1, variable2] )

This might be the most common form used with useEffect. We pass an array filled with all the dependencies that should trigger the callback function to run. Change in any of the variable in the list will execute the callback.

Often these include the states that have been created using useState hook.

Conclusion

Hopefully this has given you some more insight on how useEffect hook performs based on its second parameter, and why it is important for us to understand it.

--

--