Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
Why function declaration is crashing my react app?

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
      }
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

  1. You call addExercises every time the component renders.

  2. This changes the value of sum which triggers a rerender.

  3. 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]);
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda