Understanding React Hooks: useState and useEffect
Master the two most essential React hooks that power modern functional components.
Learning Objectives
- Understand the purpose and syntax of useState hook
- Learn when and how to use useEffect for side effects
- Implement proper cleanup functions in useEffect
- Avoid common pitfalls with hook dependencies
React Hooks were introduced in React 16.8 as a way to use state and other React features without writing class components. They've since become the standard way to build React applications, offering a cleaner and more intuitive API.
The useState hook is your primary tool for managing local state in functional components. Unlike class components where all state lives in a single object, useState lets you declare multiple state variables, each with their own setter function. This separation makes your code more readable and your state easier to reason about.
The useEffect hook handles side effects—operations that interact with the outside world or happen asynchronously. This includes data fetching, subscriptions, manual DOM manipulation, and timers. Understanding the dependency array is crucial: an empty array means the effect runs once on mount, while including dependencies ensures the effect re-runs when those values change.
One critical aspect of useEffect is cleanup. When your effect creates a subscription or timer, you need to return a cleanup function that tears it down. This prevents memory leaks and ensures your component doesn't try to update state after unmounting.
Practice Exercises
Create a counter component that increments by 1 when a button is clicked. Use useState to manage the count.
Hint: Remember that useState returns an array with two elements: the current value and a setter function.
Build a component that fetches user data from an API when it mounts and displays a loading state while fetching.
Hint: You'll need both useState (for data and loading state) and useEffect (for the fetch call).
Create a timer component that counts up every second and properly cleans up when unmounted.
Hint: Return a cleanup function from useEffect that clears the interval.