Interview question
What is useReducer and when should you use it? useReducer क्या है और कब use करें?
Answer
// useReducer for complex state logic
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 };
case 'RESET':
return { count: 0 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
<button onClick={() => dispatch({ type: 'RESET' })}>Reset</button>
</div>
);
}useReducer - complex state के लिए
const [state, dispatch] = useReducer(reducer, initialState);
Reducer function:
function reducer(state, action) {
switch(action.type) {
case 'ACTION':
return newState;
}
}Was this answer clear?