In React, you should never modify state variables directly or outside the component function. State should only be updated using the state setter function provided by useState
(or setState
in class components).
Common Mistakes:
- Direct modification:
myState = newValue
(wrong) - External modification: Trying to change state from outside the component
Correct Approach:
Always use the setter function inside your component:
const [count, setCount] = useState(0);
// Update correctly:
setCount(5); // Inside the component or its hooks/event handlers
If You Need External Control:
If you genuinely need to modify state from outside the component, you should:
- Pass the setter function as a prop to child components
- Use a state management solution (Redux, Context API)
- Lift state up to a common parent component
Example of Lifting State Up:
function ParentComponent() {
const [count, setCount] = useState(0);
return (
<>
<ChildComponent setCount={setCount} />
<button onClick={() => setCount(c => c + 1)}>Increment</button>
</>
);
}
function ChildComponent({ setCount }) {
// Child can now modify parent's state properly
return <button onClick={() => setCount(0)}>Reset</button>;
}