☰ See All Chapters |
React useReducer Hook
The useReducer hook is similar to the useState hook. The useReducer Hook is useful when you need to reference a previous value or when you have different actions the require complex data manipulations.
The useReducer function accepts two arguments. First is reduce function and second is initial state.
useReducer(<reducer>, <initialState>)
The reducer function contains your custom state logic and the initialState can be a simple value but generally will contain an object.
The useReducer Hook returns the current state and a dispatch method.
demo.component.js
import { 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 DemoComponent() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> Count: {state.count} <button onClick={() => dispatch({ type: 'decrement' })}>-</button> <button onClick={() => dispatch({ type: 'increment' })}>+</button> </> ); } export default DemoComponent; |
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import DemoComponent from './components/demo.component'; import reportWebVitals from './reportWebVitals';
ReactDOM.render( <React.StrictMode> <DemoComponent></DemoComponent> </React.StrictMode>, document.getElementById('root') );
reportWebVitals(); |
All Chapters