Search code examples
javascriptreactjsuse-state

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


Solution

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

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