When our components have one piece of state that depends on another, it's difficult to use the useState() Hook. This Hook comes with the assumption that when a state needs to be updated, it's one piece at a time. In real applications, there are often scenarios where updating one piece of state means that another piece of state needs to be updated as well, based on this new value.
Let's look at an example that allows the user to select an item and the quantity of that item. It then shows the cost. This means that whenever the quantity or item fields change, the total must also change. Here's the reducer code:
import React, { Fragment, useReducer, useEffect } from 'react';
const initialState = {
options: [
{ id: 1, name: 'First', value: 10 },
{ id: 2, name: 'Second', value: 50 },
{ id: 3, name: 'Third', value: 200 }
],
quantity: 1,
selected: 1
};
function reduceButtonStates(state) {
return...