Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

260
Vistas
why is my if else statement returns true two times?

so I am new to React and I am trying to learn the basics. I got stuck at a point, where I try to show/hide an element on a page. The problem is that when I click Show details, it works, but Hide details must be clicked 2 times in order to do what its supposed to do.

Can you help me understand this?

import React, { useState } from 'react'


const Playground2 = () => {

let visible = false;
const [details, showDetails] = useState();
const [buttonText, changeButtonText] = useState("Show details");

const toggleVisibility = () => {
    if (visible) {
        showDetails("");
        visible = false;
        console.log(visible);
        changeButtonText("Show details")

    } else {
        showDetails("Here are some details");
        visible = true;
        console.log(visible);
        changeButtonText("Hide details");
    }
}


return (
<>
    <section>
        <div className="container">
            <h1>Visibility Toggle</h1>
            <button onClick={toggleVisibility}>{buttonText}</button>
            <p>{details}</p>
        </div>
    </section>
</>
)
}

export default Playground2
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You should use the state in your condition. If you declare a variable like your visible one, this will be assigned on every render (every time you set the state with changeButtonText or showDetails. So every time will be set to false. You can simplify your component by doing:

import React, { useState } from 'react'


const Playground2 = () => {

const [visible, setVisible] = useState();

const toggleVisibility = () => {
    setVisible(prevState => !prevState)
}

const buttonText = visible ? 'Hide details' : 'Show details'
const details = 'Here are some details'

return (
  <>
    <section>
        <div className="container">
            <h1>Visibility Toggle</h1>
            <button onClick={toggleVisibility}>{buttonText}</button>
            {visible && <p>{details}</p>}
        </div>
    </section>
  </>
 )
}

export default Playground2
about 4 years ago · Juan Pablo Isaza Denunciar

0

Well it'd solve your problem if you turn visibility to state as well.

What I think happening is that when you click on button, the visibility variable is turned to false but component isn't refreshed. In order for component to get refreshed, there must be some change in state.

Maybe try that. That should do the trick.

Tip: Variables like loading, visibility, modal closed/open should be state variables.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Move let visible = false out of the component body and this will work as expected, since you are putting visible inside Component, every time the component updates false will be stored in visible.

let visible = false
const Playground 2 = () => {}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda