React · Lesson 3 of 15 · 3 min
State Management with useState & useEffect
This is the most common topic in React interviews. Get the lifecycle right, and you're halfway there.
How to manage component memory with useState
Functional components are just functions. On their own, they have no memory between renders. useState is the hook that gives them state.
You declare a state variable like this:
const [count, setCount] = useState(0);
This gives you two things: count, the current value (which is 0 on the first render), and setCount, a function to update it. Calling setCount tells React to schedule a re-render of your component. In that next render, the useState call will return the new value.
The trap: State updates are not synchronous. Calling setCount(count + 1) does not immediately change the value of count in the currently running code. React batches state updates for performance.
// This will not work as you expect
const handleTripleClick = () => {
setCount(count + 1); // count is 0, setCount(1) is scheduled
setCount(count + 1); // count is still 0, setCount(1) is scheduled again
setCount(count + 1); // count is still 0, setCount(1) is scheduled a third time
};
// After the next render, count will be 1, not 3.
To update state based on its previous value, always use the functional update form. It guarantees you're working with the latest state.
// This works correctly
const handleTripleClick = () => {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
};
// After the next render, count will be 3.
How to run side effects with useEffect
A "side effect" is any interaction with the world outside of your component. This includes fetching data, setting timers, or directly manipulating the DOM. You can't do this during rendering. useEffect lets you run this code after the component has rendered to the screen.
The basic structure is useEffect(callback, dependencies). The dependency array is the most important part. It tells React when to re-run your effect.
[](empty array): The effect runs only once, after the initial render. This is for setup code, like fetching initial data or adding a global event listener.[prop, state](array with values): The effect runs after the initial render, and again only if any value in the array has changed since the last render.- No array: The effect runs after every single render. This is almost always a bug and can easily cause infinite loops. Avoid it.
In an interview, you will be asked to explain the dependency array. Describe the three cases above and give a concrete example for each:
[]for initial data fetch,[userId]for re-fetching when the user changes, and omitting it as a common source of performance problems.
How to prevent memory leaks with cleanup functions
If your effect sets something up, it also needs to tear it down. Subscriptions, timers, and event listeners will live on even if your component unmounts, causing memory leaks and bugs.
useEffect handles this by letting you return a cleanup function.
useEffect(() => {
// 1. The effect runs
const timerId = setInterval(() => {
console.log('tick');
}, 1000);
// 2. You return a cleanup function
return () => {
clearInterval(timerId);
};
}, []); // Dependency array
React runs the cleanup function in two scenarios:
- When the component unmounts.
- Before the effect runs again (if a dependency has changed).
This ensures you never have multiple timers or listeners running from the same useEffect hook.
Here is a complete example of a timer that uses useState for its state, useEffect to manage the setInterval side effect, a dependency array to control it, and a cleanup function to prevent leaks.
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
const [isRunning, setIsRunning] = useState(false);
useEffect(() => {
// This effect does nothing if the timer is not running.
if (!isRunning) {
return;
}
const intervalId = setInterval(() => {
// Use a functional update to avoid a stale 'seconds' closure.
setSeconds(s => s + 1);
}, 1000);
// The cleanup function runs when isRunning changes or the component unmounts.
return () => {
clearInterval(intervalId);
};
}, [isRunning]); // Re-run the effect whenever isRunning changes.
const toggle = () => setIsRunning(!isRunning);
const reset = () => {
setSeconds(0);
setIsRunning(false);
};
return (
<div>
<h3>Timer: {seconds}s</h3>
<button onClick={toggle}>{isRunning ? 'Pause' : 'Start'}</button>
<button onClick={reset}>Reset</button>
</div>
);
}
When NOT to use useEffect
A common mistake is using useEffect to sync state that can be calculated during the render itself. This is called derived state.
The trap: Using an effect to calculate a value from other state or props adds complexity and can cause an extra, unnecessary re-render.
// BAD: Using an effect for derived state
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);
// GOOD: Calculating derived state during render
const fullName = `${firstName} ${lastName}`;
If you can compute it during the render, do it. It's simpler, more efficient, and avoids a class of bugs related to out-of-sync state. Only use useEffect when you need to interact with the outside world.
Try it
Build a component that displays the current browser window width and height. Use useState to store the dimensions. Use useEffect to add a resize event listener to the window object when the component mounts, and make sure to remove it in a cleanup function when the component unmounts.
Next: Learn how to display dynamic content with Conditional Rendering & List Management.
Lock it in — apply this lesson under interview conditions.