-
Notifications
You must be signed in to change notification settings - Fork 0
Notes useReducer
ZhengLin Li edited this page Jan 8, 2023
·
1 revision
-
reducer
: The reducer function that specifies how the state gets updated, should take the state and action as arguments, and should return the next state. -
initialArg
: The value from which the initial state is calculated. It can be a value of any type. -
optional
init
: If it’s not specified, the initial state is set to initialArg.
useReducer returns an array with exactly two values:
-
The current state. During the first render, it’s set to init(initialArg) or initialArg (if there’s no init).
-
The dispatch function that lets you update the state to a different value and trigger a re-render.
-
action
: The action performed by the user. It can be a value of any type. By convention, an action is usually an object with a type property identifying it and, optionally, other properties with additional information.
- dispatch functions do not have a return value.
npx create-react-app my-app
import { useReducer } from 'react';
function App() {
function reducer(state, action) {
if (action.type === 'incremented_age') {
return {
age: state.age + 1,
};
}
throw Error('Unknown action.');
}
const [state, dispatch] = useReducer(reducer, { age: 42 });
return (
<>
<button
onClick={() => {
dispatch({ type: 'incremented_age' });
}}
>
Increment age
</button>
<p>Hello! You are {state.age}.</p>
</>
);
}
export default App;
_Footer