Avoid a long list of React Providers

Julius Koronci
1 min readSep 23, 2019

With all the new cool context and hooks features, we sometimes end up with a component consisting of a long list of nested providers. This is often hard to read and is too much visual clutter.

I didn’t find any easy way of composing Providers so I came up with my own little hack.

import React, { FC, ComponentType, Fragment } from 'react';

type Components = ComponentType | [ComponentType, { [key: string]: any }];

interface Props {
components: Components[];
}

export const Compose: FC<Props> = ({ components, children }) => (
<Fragment>
{components.reverse().reduce((acc, curr) => {
const [Provider, props] = Array.isArray(curr) ? [curr[0], curr[1]] : [curr, {}];
return <Provider {...props}>{acc}</Provider>;
}, children)}
</Fragment>
);

The compose component :)

It doesn’t do much but it allows you to do one crazy thing and that is:

<Compose components={[
[
Provider, { store }],
PluginProvider,
ThemeProvider,
PreloadContainer,
SnackbarProvider,
AclProvider,
DebugPanelProvider,
]}>
...content</Compose>

This will basically take every single component in order and nest it inside the next one, if the component is an array it will also spready the object at the second position.

Dunno if this is the best solution but I kind of like it, hope someone will find it useful :)

--

--