Home
Basics
Introduction Setting up environment First Component JSX Component lifecycle Class Based Components Function Based Components Props State Hooks useState hook useEffect hook Events Server requests CSS in React Router third party JavaScriptAdvanced
useContext hook useRef hook useReducer hook Memo useCallback hook Custom Hooks React and ReduxMiscellaneous
React Third Party Components Html templates in React React Interview QnAuseReducer in react
useReducer hook is an alternative way to manage state in React application. useState hook is suitable for managing simple states. here is why you should consider using useReducer hook over useState.- When state is a complex object, it is easier to manage state
- When new state depends on previous state, it is easy to update state
- Single reducer functions can handle multiple action types
import { useReducer } from "react";
const counterReducer = (state, action) => {
console.log(state, action);
switch (action.type) {
case "INCREMENT":
return { ...state, count: state.count + 1 };
case "DECREMENT":
return { ...state, count: state.count - 1 };
default:
return state;
}
};
export default function App() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<div>
<h1>Counter example using useReducer hook</h1>
<div>Count:{state.count}</div>
<button onClick={() => dispatch({ type: "INCREMENT" })}>+</button>
<button onClick={() => dispatch({ type: "DECREMENT" })}>-</button>
</div>
);
}
Web development and Automation testing
solutions delivered!!