Advantages of rendering a component vs a function returning JSX [React]

Viewed 1667

I understand that, within your React component, it's always good to render a component rather than use a function that renders some JSX. What I mean is,

Doing this :

export default function App() {
  const [count, setCount] = useState(0);
  const someRenderFunction = () => <p>Hey</p>;
  return (
    <div className="App">
      {someRenderFunction()}
      <button
        onClick={() => {
          setCount((c) => c + 1);
        }}
      >
        Increment{" "}
      </button>
      <p>{count}</p>
    </div>
  );
}

is NOT encouraged. The render function should be exported into it's own Component, like this :

const HeyComponent = () => <p>Hey</p>

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div className="App">
      <HeyComponent />
      <button
        onClick={() => {
          setCount((c) => c + 1);
        }}
      >
        Increment{" "}
      </button>
      <p>{count}</p>
    </div>
  );
}

But I never really understood the benefits of this refactor. I tried placing checking the re-render behaviours, unmount behaviours. Still didn't see any difference. Can anyone explain in detail why this refactor is necessary/beneficial ?

3 Answers

This is all about components, so components should be reusable and should follow the DRY principle, in your case that seems to be so simple and just as you said will prevent the someRenderFunction() to be re-rendered if there aren't any changes to that component in the virtual dom so the best practices are to use <X /> syntax always or for some cases const Y = <X /> also is more readable. testing is another reason to create more components and make them more decoupled. imagine here you need to pass props to your someRenderFunction() so you will lose the jsx feature for passing props as <X prop={PROP}/>.

The actual difference between the two is that the function returning JSX is not a component, so it does not have its own state. When you use useState in the function, the state change will cause the App to be re-rendered.

The code which renders a component is followed as best practice. Using Components we can pass state values to child component and can be used to display data. The same component can be re-used in other places.

If you have to just display a small function it can be used too if it shows constant information.

Related