In React, useReducer
is a Hook that provides a way to share and manage state in functional components. It is an alternative to useState
, and can be useful for managing more complex state changes.
Here's an example of how to use useReducer
:
index.tsx710 chars30 lines
In this example, we create a reducer function that takes a state object and an action object, and returns a new state object based on the action type. We also set an initial state.
In the Counter
component, we use useReducer
to create a state object and a dispatch
function. We pass in the reducer function and initial state as arguments to useReducer
.
We render the current count from the state object, and provide buttons that dispatch actions to increment or decrement the count. These actions are handled in the reducer function.
Note that useReducer
can also accept a third argument, which is a function to initialize the state. The third argument is useful when you need to compute the initial state based on props.
gistlibby LogSnag