Let's suppose that we have a component that counts the total money of a group of people:
jsximport React, { useEffect, useState } from 'react'; const totalMoney = () => { const [total, setTotal] = useState(0); // Data could be an external json, but let's take a simple example // BTW: I don't have anything to do compared to these big fishes 😝 let people = { 'Erik': {money: 2500}, 'Musk': {money: 350000000}, 'Bezos': {money: 450000000000} }; // We count the total of money on the first load of the component useEffect(() => { // 'total' is the previous state value Object.keys(people).map(name => setTotal(total => total + people[name].money)); }, []); return( <div>The total amount of money is {total} $.</div> ); } export default totalMoney;
You can set new state by using the previous value.
Think if it's worth it to set the state so many times. On this example, instead of using a map()
, you could use reduce()
and increase the efficiency of the code.
Example:
jsxuseEffect(() => { // Reduce function returns a single value as a result of operating with an array let total = Object.values(people).reduce((acc, {money}) => acc += money, 0); // On the previous example, you set the state 3 times, here you only set it once setTotal(total); }, []);
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.