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

272
Visualizações
I want to only a single component update on state change

I want to update only a single element when using setState in a function

import { useState } from "react";

export default function App(){

  const [state, setState] = useState("foo");

  return(

    <Component1/>
    <Component2/>
    <Component3/>

  );


}

I need some way of updating one some of those elements, but not all.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In functional components, you can wrap your component with React.memo. With this way, React will memorize the component structure and on next render, if the props still the same, React does not render again and use the memorized one. For more information, https://reactjs.org/docs/react-api.html#reactmemo

Basically wrap with React.memo. Below code, when state1 change, Component2's render count won't increase because its props stays same. But when state2 change, both of them will render.

export const Component2 = React.memo(({ state2 }) => {
  const renderCount = useRef(0);
  renderCount.current = renderCount.current + 1;
  return (
    <div style={{ margin: 10 }}>
      Component2(with React.memo): <b>Rendered:</b> {renderCount.current} times,{" "}
      <b>State2:</b> {state2}
    </div>
  );
});

export default function App() {
  const [state1, setState1] = useState(1);
  const [state2, setState2] = useState(1);
  return (
    <div className="App">
      <div onClick={() => setState1((state) => state + 1)}>
        Click to change state1
      </div>
      <div onClick={() => setState2((state) => state + 1)}>
        Click to change state2
      </div>
      <Component1 state1={state1} />
      <Component2 state2={state2} />
    </div>
  );
}

I created a sandbox for you to play. Click the buttons and see React.memo in action. https://codesandbox.io/s/xenodochial-sound-gug2x?file=/src/App.js:872-1753

Also, with Class Components, you can use PureComponents for the same purpose. https://reactjs.org/docs/react-api.html#reactpurecomponent

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