0 results found in this keyword

How to use useReducer in React Hooks


The word “reducer” may evoke pictures of revived – however, I promise you don’t ought to perceive revived to scan this post, or to use the new useReducer hook that comes with the React 16.8.

React Hooks API is formally free in React 16.8. In this post, we have a tendency to focus particularly on useReducer by introducing varied use cases. Before you continue reading this tutorial, please scan the papers if you haven’t. This tutorial assumes readers have already got a basic understanding of hooks.

If you're the least bit accustomed to reducers, you must have an honest understanding of what React’s useReducer hook will. Plain and straightforward, it permits purposeful elements in React access to reducer functions from your state management. If you're not accustomed to reducers, scan this Reducers Introduction initial.
 

In this post, we’re watching the useReducer hook. It’s nice for managing a lot of difficult state than you'd need to manage with useState on its own.

What’s a Reducer?

A “reducer” may be a fancy word for a perform that takes a pair of prices and returns one value.

An alternative to useState. Accepts a reducer of kind (state, action) => newState, and returns the present state paired with a dispatch methodology.

const [state, dispatch] = useReducer(reducer, initialArg, init);

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.

Example

Specifying the initial state

const [state, dispatch] = useReducer( reducer, {count: initialCount} );
function init(initialCount) { return {count: initialCount};}

function reducer(state, action) {

switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
case 'reset':
return init(action.payload);
default:
throw new Error();
}
}


function Counter({initialCount}) {

const [state, dispatch] = useReducer(reducer, initialCount, init); return ( <>
Count: {state.count}
<button
onClick={() => dispatch({type: 'reset', payload: initialCount})}> Reset
</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}

Chandan Kr. Singh
Chandan Kr. Singh

Web Developer

chandansingh16794@gmail.com

I'm a Web Application Developer with 2 years of experience. Currently, I'm working on front-end & back-end web development using popular web technology Languages. That's why I love to share my coding knowledge in a smart way.

Leave a Comment