HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

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:

  • 'useReducer' is called with the 'reducer' function and an initial state ('initialState').
  • The 'reducer' function takes the current state and an action, and it returns the new state based on the action.
  • The state and a 'dispatch' function are returned by useReducer. The dispatch function is used to trigger state transitions by dispatching actions.