Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda