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

225
Visualizações
Toast displaying twice on React page render - why does it happen multiple times?

I'm dipping my toes in the React pool and can't seem to get my head round one aspect mainly around the amount of times the function renders the page.

Using the below example when the form validation fails I see the toast display TWICE.

The toast I am using is react-hot-toast

My understanding is that;

  • The page first renders and formErrors from the useState() is empty.

  • When the submit button is pressed it calls the onSubmit function and if the form fails validation it fires setFormErrors function

  • This causes a re-render of the page, while also populating the formErrors variable

  • As formErrors is not falsy etc it then fires the toast function.

But when I check the console I see it has fired toast twice and I see two toasts, this means it's rendered twice? Why is this?

Am I going about this all the wrong way? Is there a better method of using a function like toast to display messages? Should I be putting it all in a context (might not be right terminology) ?

export default function RegistrationPage() {
    const [formErrors, setFormErrors] = useState({})
  
    const passwordField = useRef()   
    const password2Field = useRef()

    useEffect(()=>{
        usernameField.current.focus()
    })

    const onSubmit = (ev) =>{
        ev.preventDefault()
        if(passwordField.current.value !== password2Field.current.value){
            setFormErrors({"password2": "Passwords do not match"})
        }else{
           console.log("Need to implement")
        }
    }

    if(formErrors && Object.keys(formErrors).length > 0){
        toast('Here is your toast.');
        console.log("Toast Fired");
    }

    return (
        <Body>
            <h1>Login</h1>
            <Form onSubmit={onSubmit}>
                <InputField fieldRef={usernameField} name="username" label="Username" error={formErrors?.username}></InputField>
                <InputField fieldRef={emailField} name="email" label="Email Address" type="email" error={formErrors?.email}></InputField>
                <InputField fieldRef={passwordField} name="password" label="password" type="password" error={formErrors?.password}></InputField>
                <InputField fieldRef={password2Field} name="password2" label="password again" type="password" error={formErrors?.password2}></InputField>
                <Button variant="primary" type="submit">Register</Button>
            </Form>
        </Body>
    );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I am not familiar with the <InputField> but I reckon error gets displayed right? It probably toasts and then rerenders the error and then toasts again after because you still have the error there.

What you probably want is useEffect(() => { //Code you want excecuted like toasting / alerting }, [formErrors]); Which fires the code in the useEffect scope everytime the variable in the array gets updated. Or you'd want to toast inside the scope that sets the form error which is simpler and arguably more elegant.

Also this is me being nosy but these inputfields could be self closing like this : <InputField props={props} /> UX wise its also probably better to show invalid input before the user clicks register or to also stop them from clicking it all together. Hope this helps, happy coding!

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