UseEffect Rules, Best Practices, and Misuses


UseEffect hook is a useful tool but it should be your Last Resort, consider other alternatives first.
We will talk about useEffect Rules, best practices, and when it's overused.
Having unnecessary dependencies in the dependencies array can cause unnecessary rerenders. Which may slow your application.
Here's how you can avoid unnecessary dependencies.
Instead of including the entire object, include only the properties you need.
Example:
user and you only use user.id in your effect, include only user.id in the dependency array. (check the example below)
If that doesn't work, Apply the same strategies mentioned for functions.
If you have many related reactive values as dependencies. Try to store them in a reducer (useReducer).
PS: You don't need to include these hooks in the dependencies:
-> React guarantees them to be stable across renders.
It's okay to use it in small apps. Otherwise, you should use libraries like React Query.
Use event handler functions instead.
It means setting a state based on another state variable. Instead, Try to use derived state and event handlers.
There are some exceptions, let's take this example.
Imagine We wanna compute a Duration state, based on other vars (number, sets, speed, and durationBreak). In the example below. We call the calculateDuration function after each update of the state vars.
It's working but it's redundant.
It's cleaner to have a UseEffect that will recalculate the Duration whenever one of the state variables changes, like in the code below.
UseEffect is a powerful hook for managing side effects in React. Understanding when and how to use it is a must.
Those were my notes from Jonas's react course.
If you have any thoughts or questions, feel free to reach out to me on Twitter or LinkedIn.
Get notified when we publish new blog posts
Comments