React useState and useReducer
Snippets
// this will return an array [100,f]
// basically this returns a state and a function to update the state
// we can destructure the array and get the state and the function
const [state, setState] = useState(100);
// you pass function in useState it will set the initial value to what function returns
// it is useful when you use computationaly high task as initial state
const [state, setState] = useState(() => {
console.log("initial state");
return 100;
});
onClick={() => {
// here value in the props is the state
setState((value) => {
//you can use this method when you need to update the state from a previous state value
return value + 1;
});
}}
Context
- State Management — Where hooks fit in the state landscape
- Zustand — When local state outgrows useState
- Hydration — Server-client state handoff pitfalls
- React Components — The component model hooks serve
Questions
When does useReducer earn its complexity over useState?
- What state shape signals "switch to a reducer"?
- How do you test reducer logic independently of the component?
- When does a growing reducer mean you need a state library instead?