Home > Mobile >  useState for event handler without callback
useState for event handler without callback

Time:06-15

In the code below

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 handleClick1 = useCallback(() => {
    console.log(channel);
  }, [channel]);

  const handleClick2 = () => {
    console.log(channel);
  };

  const parentClick = () => {
    console.log("parent is call");
    setChannel((prev) => prev   1);
  };
  // useEffect(() => {
  //   setChannel(1);
  // });
  return (
    <div className="App">
      <button onClick={parentClick}>parent click</button>
      <br />
      <br />
      <button onClick={handleClick1}>child click1</button>
      <button onClick={handleClick2}>child click2</button>
      &nbsp;
    </div>
  );
};

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

There is one child click wrap with callback (handleclick1) and one didn't (handleclick2). After parent click, both children get the right channel state value. My question is for handleclick2 :

  1. will the change of channel state value trigger the re-evaluation of the function and hence rerendering of the entire UI?
  2. If the answer for 1 is no, then how the function got the right value of channel state value?

see codesandbox here

CodePudding user response:

will the change of channel state value trigger the re-evaluation of the function and hence rerendering of the entire UI?

Yes, but this isn't due to anything in handleClick2 - it's due to the state setter being called. Whenever a state setter is called, the component will re-render - which means, in this case, that the App function runs again.

useCallback is usually useful when passing down a function to another React component as a prop, to reduce that component's need to re-calculate things. It's not useful in situations like these where everything is done in a single component.

  • Related