Master a Hidden React Optimization Technique Few Engineers Know

This one optimization trick on React, only a few engineers know about.

I've been working with React for over 5 years, and during that time, I've had the opportunity to explore various codebases. I've noticed a common mistake that can affect app performance, and I thought it might be helpful to share it.

React completely based on the design pattern of component composition. Only a few engineers know how we can leverage the component composition to make our application optimized.

We all are very well aware of the rule if any component in React let's say “Child” is created inside the “Parent”, then every time “Parent” is re-rendered it re-renders “Child” too.

Why the React is doing that?

Because creating a child inside the parent causes the child component to be recreated every time the parent component is rendered.

How we can solve this problem?

With the help of correctly using component composition patterns.

if “Child” will be rendered inside Parent but not created inside “Parent”, then this problem can be solved.

We can achieve that by passing the <Child /> element as a prop of Parent, React even has a prop created specifically for that called “children”

When the Parent component is re-rendered, the Children does not re-render. This occurs because Children are not created during the call to Parent, but rather beforehand within the App component.

I often share nuances and caveats about different technologies you can consider follow me to learn these great things.


// ❌ Not recommended:
// Avoid creating components inside other components
// This will cause the child component to be recreated every time the parent component is rendered

export default function App() {
  return <Parent />
}

const Parent = () => {
  const [count, setCount] = useState(0)

  console.log('Parent rendered!')

  return (
    <>
      <button onClick={() => setState((prevCount) => prevCount + 1)}>Increment Count</button>
      <Child /> {/* Notice that Child is created INSIDE the Parent component */}
    </>
  )
}

const Child = () => {
  console.log('Child rendered!')
  return null
}

// ✅ Recommended:
// Create the child component outside the parent component
// This way, the child component will not be recreated every time the parent component is rendered

export default function App() {
  return (
    <Parent>
      <Child />
    </Parent>
  )
}

const Parent = (children) => {
  const [count, setCount] = useState(0)

  console.log('Parent rendered!')

  return (
    <>
      <button onClick={() => setState((prevCount) => prevCount + 1)}>Increment Count</button>
      {children}
    </>
  )
}

const Child = () => {
  console.log('Child rendered!')
  return null
}