Chapter 6: State Basics
Chapter 6 of 15
Chapter 6: State Basics
6.1 useState Hook
State allows components to store and update data. useState is the hook for managing component state.
import { useState } from 'react';
function Counter() {
// useState returns [value, setter function]
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
useState Syntax:
- Returns array with [currentValue, setterFunction]
- Initial value passed as argument
- Setter function updates state and triggers re-render
- State persists between re-renders
State Updates:
// Direct value
setCount(5);
// Function update (when new state depends on previous)
setCount(prevCount => prevCount + 1);
// Multiple state variables
const [name, setName] = useState(');
const [age, setAge] = useState(0);
const [email, setEmail] = useState(');
6.2 State vs Props
Understanding when to use state vs props.
Props:
- Passed from parent
- Read-only
- External data
State:
- Internal to component
- Can be updated
- Component-specific data
6.3 State Best Practices
Follow best practices for state management.
- Keep state as local as possible
- Lift state up when multiple components need it
- Don't mutate state directly
- Use functional updates when state depends on previous value
- Initialize state with appropriate default values