useReducer is a React Hook used to manage complex state logic.
It is an alternative to useState.
Syntax:
const [state, dispatch] = useReducer(reducer, initialState);
Simple – Counter:
import React, { useReducer } from 'react';
function App() {
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case "increment":
return state + 1;
case "decrement":
return state - 1;
case "reset":
return 0;
default:
return state;
}
};
const [count, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => dispatch("increment")}>+</button>
<button onClick={() => dispatch("decrement")}>-</button>
<button onClick={() => dispatch("reset")}>Reset</button>
</div>
);
}
export default App;
Top comments (0)