๐ ๐ฎ๐๐๐ฒ๐ฟ๐ถ๐ป๐ด ๐ฅ๐ฒ๐ฎ๐ฐ๐ ๐๐ผ๐ผ๐ธ๐
I used to struggle with React.
When I built my first todo app, the UI would flicker. The state would reset. I spent hours chasing bugs. I tried to manage the UI like a static HTML page. I manually toggled classes and fought the DOM.
This approach failed. My components re-rendered constantly. I created infinite loops that froze my browser.
I had to stop fighting the UI and start letting React manage the state. That is where hooks change everything.
useState and useEffect are essential tools.
useState manages state that persists across renders. You store a value, and React remembers it. It triggers a re-render only when that value changes.
useEffect handles side effects. It runs after a render to sync your app with the outside world. Use it for APIs, timers, or subscriptions.
The most important part is the dependency array.
If you leave it out, your effect runs after every single render. This causes the infinite loop trap. If you use the wrong dependencies, you get stale data.
Here is how to avoid common mistakes:
- Use the dependency array to tell React exactly when to run an effect.
- If you fetch data based on a prop, put that prop in the array.
- Use the functional updater pattern in state setters to get the latest value.
Mastering these tools brings three main benefits:
- Predictability: Your UI stays in sync with your data.
- Performance: You avoid unnecessary network requests and calculations.
- Composability: You can create custom hooks to reuse logic across your app.
Stop micromanaging the DOM. Describe what your UI should look like based on your state, and let React do the work.
Try this today: Take an old component and refactor it using hooks.
- Identify the state that drives your UI.
- Wrap side effects in useEffect.
- Add the correct dependencies.
- Check your network tab to ensure requests fire only when needed.