30% offEnding soon
All questions

withLoading

Premium

withLoading

A higher-order component is a function that receives a component and returns a new component with shared behavior. Implement withLoading so the enhanced component chooses between a loading branch and the wrapped content. The wrapper must preserve ordinary props, children, refs, and a useful name for React DevTools.

Signature

function withLoading(
  WrappedComponent,
  LoadingComponent = null,
): React.ForwardRefExoticComponent;

// Reserved enhanced props:
// isLoading?: boolean       // defaults to false
// loadingProps?: object     // defaults to {}

Examples

const LoadableProfile = withLoading(Profile, Spinner);

<LoadableProfile user={ada} isLoading={false} />;
// Renders <Profile user={ada} />.
<LoadableProfile
  user={ada}
  isLoading={true}
  loadingProps={{ label: 'Loading profile' }}
/>;
// Renders <Spinner label="Loading profile" /> without mounting Profile.

Notes

  • Choose exactly one branch — only isLoading === true selects the loading component; omitted or other values select the wrapped component.
  • Reserve wrapper props — never pass isLoading or loadingProps to the wrapped component, and pass only loadingProps to the loading component.
  • Forward the ref — use React.forwardRef so the caller can reach the wrapped component's DOM node or imperative handle.
  • Name the wrapper — set displayName from the wrapped component's displayName, then its name, then Component.
  • Keep the scope narrow — do not mutate the wrapped component, hoist statics, copy defaultProps, memoize, fetch data, or create the HOC during render.