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

208
Visualizações
Why does the setState fn needs to be called through another function?

Lets look at the code below

import React from "react"

export default function App() {
    const [isGoingOut, setGoingOut] = React.useState(false);
    
    function yeet() {
        setGoingOut(prevValue => prevValue ? false : true);    
    }
    
    return (
        <div className="state">
            <h1 className="state--title">Do I feel like going out tonight?</h1>
            <div className="state--value" onClick={yeet}>
                <h1>{isGoingOut ? "Yes" : "No"}</h1>
            </div>
        </div>
    )
}

I'm calling the set function setGoingOut() through the function yeet(). However, if I directly call the setGoingOut() function as below

import React from "react"

export default function App() {
    const [isGoingOut, setGoingOut] = React.useState(false);
    
    setGoingOut(prevValue => prevValue ? false : true);
    
    return (
        <div className="state">
            <h1 className="state--title">Do I feel like going out tonight?</h1>
            <div className="state--value" onClick={setGoingOut}>
                <h1>{isGoingOut ? "Yes" : "No"}</h1>
            </div>
        </div>
    )
}

it throws an error. Is this related to the React philosophy of not letting the state be changed directly (the same reason we can't change a state variable count as count++ but have to do count + 1?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the first code snippet, you are calling yeet which inside change isGoingOut using setGoingOut. This will surely works

function yeet() {
  setGoingOut((prevValue) => (prevValue ? false : true));
}

In the second snippet, you are changing state directly which will create infinite loop and produces error as:

Too many re-renders. React limits the number of renders to prevent an infinite loop.

You should change state not every time, but only when user clicks the button

setGoingOut(prevValue => prevValue ? false : true);

But, If you are trying to call directly setGoingOut then what it will do is:

  1. Pass event object to setGoingOut which will become value of isGoingOut and then you can't change its value because you are setting the state of isGoingOut as a new event object particularly SyntheticEvent that React send as an argument.

    onClick={setGoingOut}
    

This is not the way you should change state.

You can change state on click as:

<div
  className="state--value"
  onClick={() => setGoingOut((prevValue) => (prevValue ? false : true))}>
  <h1>{isGoingOut ? "Yes" : "No"}</h1>
</div>
about 4 years ago · Juan Pablo Isaza 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