I am trying to calculate the total of my courses. I am passing a function declaration to the course but it is crashing my app. I am trying to setSum inside an addExercises function.
I have a component named Content:
function Content({ parts }) {
const [sum, setSum] = useState(0)
return (
<div>
{parts.map(part => (
<Part name={part.name}
exercise={part.exercises}
key={part.id}
addExercises={() => setSum(sum + part.exercises)} />
))}
Total Exercises: {sum}
</div>
)
}
Then I have a component Part: -
function Part({name, exercise, addExercises}) {
addExercises();
return (
<div>
<p>{name} {exercise}</p>
</div>
)
}
I am passing this data to content as props: -
parts: [
{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
}
You call addExercises every time the component renders.
This changes the value of sum which triggers a rerender.
GOTO 1
You have an infinite loop.
Maybe you want your function call inside useEffect hook.
Maybe you shouldn't pass it down to the component at all, but put a useMemo hook in the parent component which generates the sum by looping over the array separately.
function Content({ parts }) {
const sum = useMemo(() => {
return parts.reduce(
(total, part) => {
return total + part.exercises;
},
0
);
}, [parts]);