The useReducer hook
useReducer Hook provides an alternative to useState for managing complex state logic. It’s often used when state transitions depend on the previous state or when the next state depends on the previous state.
Syntax:
const [state, dispatch] = useReducer(reducer, initialState);
- Here, ‘initialState‘ is the initial state of the component.
- ‘state‘ is the current state value.
- ‘dispatch‘ is a function used to dispatch an action to update the state.
Example: Below is an example of useReducer hook.
import React, { 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 Gfgarticle() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<br></br>
<button onClick={() => dispatch({ type: 'increment' })}>
Increment
</button>
<button onClick={() => dispatch({ type: 'decrement' })}>
Decrement
</button>
</>
)
};
export default Gfgarticle;
Output:
Additional Built-in Hooks in React
Hooks are functions that allow you to “hook” into the state of a component and provide additional features to ensure the lifespan of functional components. These are available in React versions 16.8.0 and higher. however, we previously used to describe them using classes.
We will discuss the various Additional Built-in Hooks:
Table of Content
- The useReducer hook
- The useRef hook
- The useCallback Hook
- The useMemo Hook
- The useLayoutEffect Hook
- The useImperativeHandle Hook
- The useDebugValue Hook
- Conclusion