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

162
Vistas
useState in onclick handler

Here's the UI

enter image description here

Where I click the first button, then click the second button, it shows value 1, but I expect it to show value 2, since I set the value to 2. What's the problem and how should I address that?

Here's the code:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import React, {
  useState,
  useEffect,
  useMemo,
  useRef,
  useCallback
} from "react";

const App = () => {
  const [channel, setChannel] = useState(null);

  const handleClick = useCallback(() => {
    console.log(channel);
  }, [channel]);
  
  const parentClick = () => {
    console.log("parent is call");
    setChannel(2);
  };
  useEffect(() => {
    setChannel(1);
  });
  return (
    <div className="App">
      <button onClick={parentClick}>Click to SetChannel 2</button>
      <button onClick={handleClick}>Click to ShowChannel 2</button>
    </div>
  );
};

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<App />);

Here's the codesandbox

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

Add a dependency to the useEffect hook, if you don't add any dependency it will just re-run on every state change.

Change this:

  useEffect(() => {
    setChannel(1);
  });

To this:

  useEffect(() => {
    setChannel(1);
  }, []);
about 4 years ago · Santiago Gelvez Denunciar

0

useEffect(() => {
    setChannel(1);
  });

Runs on every render, so it's always reverting back to 1

about 4 years ago · Santiago Gelvez Denunciar

0

Your problem is that you are setting channel value to 1 every render. You have 2 options.

  • Set initial state value of channel to 1 (see below)
  • Call this.setState({channel: 1}) in the componentDidMount method.

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {channel: 1};
    }

    handleClick=(evt)=> {
        console.log(this.state.channel);
    }

    parentClick=(evt)=> {
        this.setState({channel: 2});
    }

    render() {
        return (
            <div className="App">
                <button onClick={this.parentClick}>Click to SetChannel 2</button>
                <br /><br />
                <button onClick={this.handleClick}>Click to ShowChannel 2</button>
            </div>
        );
    }
}

PS: It's not clear what you're trying to do & your sandbox is quite different from the code you have posted here.

about 4 years ago · Santiago Gelvez 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