React for JavaScript Programmers V supplemental: useReducer hook

I've mentioned useState and useEffect hooks before, but the third hook, useReducer, deserves a special mention.

Reducer is based on the "reduce" function for an array, which is a strange mix of iteration from left to right, and summation function. It has a cousin reduceRight which iterates from right to left. Most tutorials just go over it as if it is only good for calculating a "running sum" of the array by iterating over the array, but in React, a reducer function is much more powerful than that.

Think of reducer as this

reducer(prevState,currentAction) => newState

Using the previous state, and a parameter describing the current action, a new state is calculated.

The usual use for this is to have a list of actions, and perform it to the state, usually in a list of switch...case statements.

Indeed, the idea is to take a whole array of data, and to reduce it down to a single result.

The official React.js tutorial has a counter example, where the two actions are INCREMENT and DECREMENT. Buttons fire up the action, and action is passed into the reducer, which is basically doing switch...case on the action, and return a new "count" that is based on the old count value and the action.

To expand upon this idea, you can easily do a calculator, where each of the buttons is an action, and state is more complicated than just a value or two.

A shopping cart is another possibility where actions such as ADD_ITEM and REMOVE_ITEM are used to update the running_total as a state, as well as update inventory count.

You can technically write this with just useState, but useReducer is more elegant and enables you to write less code.

Also, useReducer allows you to create more complicated state transitions that should be performed together, instead of multiple state updates.

Comments

Popular posts from this blog

Yet another take on recursion

Problem Solving for Programmers: a Neglected Topic?

How to Solve a Problem, with Examples