The useReducer hook is a state management hook in React that provides an alternative to the useState hook. It is used when the state of a component is complex and requires more than one state variable.
Syntax:
const [state, dispatch] = useReducer(reducer, initialState, init)
reducer: The reducer is a function responsible for defining how the state transitions from one state to another based on dispatched actions. It takes two arguments: the current state and the action being dispatched.
initialState: initialState is the initial state value for the state managed by the reducer. It can be of any data type: object, array, number, string, etc., depending on the requirements of your application. It represents the initial state of your component before any actions are dispatched.
(optional) init : init is an optional initialisation function that can be used to compute the initial state lazily. It is a function that returns the initial state value. If provided, it is called once during the initial render, and its return value is used as the initial state.
Steps to Create a React Application :
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Example 1: Counter Application
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
export default Counter;
Top comments (0)