Sajal Shrivastav’s Post

If props don’t change, why does a component still re-render? Many developers believe that if the props are the same, the component won’t re-render. However, this isn't always the case. Consider the following example: function Parent() { const [count, setCount] = useState(0); return <Child name="Sajal" />; } In this scenario, even though the name prop never changes, the Child component will still re-render. This happens because when the Parent component re-renders, React re-runs the Child component as well. So, how can we prevent unnecessary re-renders? The solution is to use React.memo. This function tells React to only re-render the component if the props actually change. Here’s how it looks: const Child = React.memo(({ name }) => { console.log("Rendered"); return <div>{name}</div>; }); With this implementation, the Child component will not re-render unless the name prop changes. Key Insight: React re-renders by default, and optimization is something you explicitly control. Important Note: React.memo uses shallow comparison, so objects and functions may still cause re-renders. #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #SoftwareEngineering #CodingJourney #LearninglnPublic #DeveloperLife #ReactInternals #FrontendEngineer #TechInterview #StateManagement

To view or add a comment, sign in

Explore content categories