Skip to main content

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;
});
}}