Understanding useState
The useState hook is the most fundamental hook in React. It allows functional components to have state, replacing the need for class components in most cases.
When you call useState, you get back an array with two elements: the current state value and a function to update it. React ensures that the state updater function identity is stable and won't change on re-renders.
Managing Side Effects with useEffect
The useEffect hook lets you perform side effects in functional components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
Common Pitfalls
- Forgetting dependency arrays leads to infinite loops
- Missing dependencies causes stale closures
- Not cleaning up subscriptions causes memory leaks
Always be mindful of your effect dependencies and cleanup functions!