ReactJS Tips & Tricks: Avoid Nested Render Functions
Helder Burato Berto

Helder Burato Berto @helderberto

About: Software Engineer who loves to craft challenging projects and share knowledge with people.

Location:
Portugal
Joined:
Oct 15, 2017

ReactJS Tips & Tricks: Avoid Nested Render Functions

Publish Date: Nov 10 '21
10 5

A common thing I noticed in a lot of projects I worked on is the Nested Render Functions approach to render UI elements.

Let's dive into this approach and how to change in a better way.

What are Nested Render Functions?

Basically, it is when you declare a part of UI render in a function inside of a component, such as:

const Component = () => {
  function renderSection() {
    return <section>This is my section.</section>
  }

  return (
    <div>
      {renderSection()}
      ...
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Since components are just functions, it is the same as declaring new components inside the current Component.

Extracting to a New Component

It is much better to extract to a new component, it will help you to create unit tests more easily and isolated to the component.

Let's re-create the example I mentioned before, like the following:

const Section = () => <section>This is my section.</section>

const Component = () => (
  <div>
    <Section />
    ...
  </div>
)
Enter fullscreen mode Exit fullscreen mode

Instead of using closures, now you have a pure function for Section component, that's more readable and easy to give their props.

Wrapping Up

With this approach, you will create more deterministic components taking the benefit of React pure component.

It will help you to test the component and create isolated behaviour for every component.

Comments 5 total

  • Sushant Garudkar
    Sushant GarudkarNov 12, 2021

    Loved the post!!

  • Delcio Polanco
    Delcio PolancoNov 12, 2021

    Do you recommend do this also for handlers events functions ?

    • Helder Burato Berto
      Helder Burato BertoNov 13, 2021

      If you are talking about cases like this:

      const Component = ({ onClick }) => {
        const handleClick = () => {
          onClick();
        }
      
        return <button onClick={handleClick}>Click me!</button>;
      }
      
      Enter fullscreen mode Exit fullscreen mode

      IMO, it's totally unnecessary the handleClick if it is just to trigger the onClick, but if you have some logic to to before trigger the onClick, it make sense to stay there.

  • eBitzu
    eBitzuNov 16, 2021

    I think you should explain why it's not ok, starting with the unnecessary creation on each re-render, which in fact triggers the returnComponent to re-render every time the Component re-renders.

Add comment