React Performance: State Placement Over Re-Renders

React re-renders are not the enemy; incorrect state placement is. A common misconception is that “too many re-renders = bad performance.” Here’s a classic mistake: ❌ Lifting state too high ```javascript function App() {   const [isOpen, setIsOpen] = useState(false);   return (   <>    <Header />    <Sidebar isOpen={isOpen} />    <Content onOpen={() => setIsOpen(true)} />   </>  ); } ``` In this example, every time `isOpen` changes, the Header, Sidebar, and Content components re-render, even if only Content cares about the state. The issue isn't with re-renders; it's about where the state lives. ✅ Better state placement ```javascript function Content() {   const [isOpen, setIsOpen] = useState(false);   return (   <>    <Button onClick={() => setIsOpen(true)} />    <Modal open={isOpen} />   </>  ); } ``` Why this works: • Re-renders are cheap. A render does not equal a DOM update. React efficiently compares trees and can bail out early. • Lifting state too high can lead to unnecessary re-renders, tighter coupling, and harder-to-reason components. The mental model I follow is to keep state as close as possible to where it’s used. Lift it only when sharing is unavoidable. Optimize after measuring, not before. Most React performance issues are architectural, not problems with React itself. #React #ReactJS #FrontendDevelopment #FrontendEngineering #JavaScript #WebDevelopment #SoftwareEngineering #PerformanceOptimization #EngineeringMindset

See more comments

To view or add a comment, sign in

Explore content categories