How to Learn React Hooks (and Stop Fighting useEffect)
The first React app I wrote with hooks had a useEffect that fetched a user profile. It worked on the first load. Then I added the user ID to the dependency array because the linter told me to, and the network tab filled up with the same request, over and over, until the tab froze. I fixed it by deleting the dependency array. That was the wrong fix, and it took me an embarrassingly long time to…
When you first started writing a React app using hooks, you encountered a problem with an `useEffect` that fetched a user profile. After adding the user ID to the dependency array, the same request kept firing, causing the network tab to freeze. You fixed it by removing the dependency array, but later realized this was the wrong approach.
To truly understand hooks, start by grasping what a render is. Every time state changes, React calls your component function again, creating fresh variables and functions. This is why logging a stale value appears when `count` belongs to a previous render.
Next, learn the updater form of `useState` early, as it's frequently used. If the new state depends on the old one, pass a function to `setCount` to ensure the correct increment. Understanding that objects in state are replaced, not merged, is also crucial.
`useEffect` is employed to sync your component with things outside React's control, like network requests or timers. The dependency array isn't just a list of when to run; it's a list of all values from the render that the effect reads. Lying with it leads to stale data. To avoid this, move functions inside effects, depend on primitive values, or question whether an effect is necessary at all.
Review common mistakes such as looping, stale data, and unnecessary effects. Reviewing these concepts over time through spaced repetition can help solidify your understanding. Consider using tools like Recl, an AI learning app, to save, summarize, and review content for better retention.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.