Pattern to handle repeated props using the React context API

Richard Samuelsson
Apr 25 · 2 min read

Let’s say that we have multiple components that need the same props


How can we avoid passing the same `onClick`, `outline` and `theme` to all these components?

It would be nice if we could consume an API like this:

How to create the used hoc and provider component

To accomplish this, we need a withProps HOC and the PropsProvider component.

Sending props in this manner requires the use of the context API.

The PropsProvider component takes `props`and `children`.

The withProps HOC returns a component that merges the provided props with the own props of the component (see allProps):

This means that you can override the props sent to the component via the HOC by adding props to returned component specifically, e.g.

An additional improvement is to allow nested PropsProviders:

To make this a reality we use consumer in the PropsProvider component, to consume already created contexts:

Here we merge the already provided props in the context, with the props prop set onto the PropsProvider (see newProps) and then just return the Provider with its value and children.

Full code:

Hope this gist saves some time

Richard Samuelsson

Written by

Full stack developer using React, RxJS, node and serverless

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade