Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
useState for event handler without callback

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!