React useReducer Hook
React useReducer
'useReducer' is a React Hook that is used for managing more complex state logic in functional components.
It is an alternative to using 'useState' when the state logic becomes more intricate and involves multiple sub-values or transitions between different states.
Here's a basic example of using 'useReducer':
import React, { useReducer } from 'react';
// Reducer function
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};
const MyComponent = () => {
// Initial state and dispatch function returned by useReducer
const initialState = { count: 0 };
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 MyComponent;
In this example: