Early Returns in React Components

> When and how should you return early in a React component?
Cover Image for Early Returns in React Components
Marcel Gruber

In continuation from my post on JSS project tips, I want to cover early returns in React components. When building a component, one must always ask, "under what conditions would this component not be displayed?"

For example:

  • Required field data is not present
  • Datasource item is null
  • No results were returned from a query / search
  • Page is in or not in edit mode
  • User is not authorized to view the component

It's one thing to ask the question, but it's another to implement properly.

What Not to Do

I was recently looking at a NextJS/JS headless build and noticed this check in a component prior to rendering the markup:


_9
if (!data) {
_9
return;
_9
}
_9
_9
return (
_9
<>
_9
<div>{data}</div>
_9
</>
_9
)

This will return an error message:

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

Had this been written in TypeScript, the error would have been caught at compile time.

Return Types

Realistically speaking, I could imagine a developer performing an early return with any of these values:


_13
// Don't do this
_13
return; // Will throw an error -- this is the same as returning undefined
_13
return undefined; // Will throw an error
_13
return '';
_13
_13
// This is the equivalent of rendering nothing and is ok
_13
return false;
_13
return null;
_13
_13
// These may be useful in certain scenarios
_13
return <div></div>;
_13
// This <></> syntax is called React Fragments. In this specific example, we're returning an empty fragment, which is equivalent to rendering nothing.
_13
return <></>;

Conclusion

Always ask under what conditions a component should not render, or under which conditions some or all of the elements within it should be hidden. React components expect you to return elements, null, or false. As always, when you are working on early returns, be sure to test in EE!

Keep learning,

MG


More Stories