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

271
Views
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 answers
Answer question

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 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!