The useReducer Hook is similar to useState but supports custom state logic. It is useful when managing multiple state values with complex logic.
The useReducer Hook takes two arguments.
useReducer(<reducer>, <initialState>) |
The reducer function handles your custom state logic, and the initialState can be a simple value but is typically an object.
The useReducer Hook returns the current state and a dispatch method.
Here is an example of useReducer in a counter app:
import
};
function
{
<label> <input type="checkbox"
checked={todo.complete}
onChange={() => handleComplete(todo)}
/>
{ </label> </div>
</>
}
const
|
This logic manages the status of whether a todo is complete.
By adding more actions, you can include all the functionality to add, delete, and complete todos within a single useReducer
Hook.