Advertisement
Intermediate React, Higher-Order Components (HOCs)

How do you properly pass through extra props when writing a higher order component?

Short answer

You spread any extra props received by the wrapper component down onto the wrapped component, ensuring the wrapped component still receives everything it normally would, plus whatever new prop the higher order component adds.

Save React mock interview
Advertisement
AModel answer
You spread any extra props received by the wrapper component down onto the wrapped component, ensuring the wrapped component still receives everything it normally would, plus whatever new prop the higher order component adds.
function withExtraData(WrappedComponent) {
  return function Enhanced(props) {
    const extraData = useExtraData();
    return <WrappedComponent {...props} extraData={extraData} />;
  };
}
Real-world example
A higher order component that adds analytics tracking data still correctly passes along every other prop the original component expected, like a title or an onClick handler, thanks to spreading the original props through.
Likely follow-ups
  • What happens if a higher order component accidentally overwrites a prop with the same name?
  • How would you rename the extra prop to avoid a naming collision?
Related topics