Don't use React.createContext(), create hooks.
Maksym Marchuk
Posted on September 4, 2024
In this article, we will look at how to get rid of React.createContext() in your apps and find a motivation for doing so.
If you landed at this article you are probably familiar with React and may have already had experience with React context, but if not, feel free to read it anyway and share it with people who might be interested.
1. Why avoid React.createContext()?
Context degrades readability, entangles and restricts the app.
Just take a look at this basic example:
<ThemeContext.Provider value={theme}>
<AuthContext.Provider value={currentUser}>
<ModalContext.Provider value={modal}>
<VolumeContext.Provider value={volume}>
<RouterProvider router={router} />
</VolumeContext.Provider>
</ModalContext.Provider>
</AuthContext.Provider>
</ThemeContext.Provider>
Doesn't look too comprehensible and reliable, does it?
Here are some potential issues when using contexts:
- The more contexts used, the less readable and controllable your app becomes;
- Sometimes nested contexts require a correct order to work, which makes your app difficult to maintain;
- Some contexts should be re-used during the setup of a test environment to keep working properly;
- You have to make sure the component is a child down the tree of a necessary context provider.
Fun fact: the well-known "promise-hell" looks alike 🤷♂️
loadClients()
.then((client) => {
return populate(client)
.then((clientPopulated) => {
return commit(clientPopulated);
});
});
2. How to replace React.createContext()?
Create hooks instead.
Let's replace ThemeContext from the example above with a custom useTheme hook:
import { useAppEvents } from 'use-app-events';
const useTheme = () => {
const [theme, setTheme] = useState('dark');
/** Set up communication between the instances of the hook. */
const { notifyEventListeners, listenForEvents } = useAppEvents();
listenForEvents('theme-update', (themeNext: string) => {
setTheme(themeNext);
});
const updateTheme = (themeNext: string) => {
setTheme(themeNext);
notifyEventListeners('theme-update', themeNext);
};
return {
theme,
updateTheme,
};
};
We used an npm package called
use-app-events
to let all instances of the useTheme hook communicate to synchronize their theme state. It ensures that the theme value will be the same when useTheme is called multiple times around the app.Moreover, thanks to the
use-app-events
package, the theme will be synchronized even between browser tabs.
At this point, ThemeContext is no longer needed as the useTheme hook can be used anywhere in the app to get the current theme and update it:
const App = () => {
const { theme, updateTheme } = useTheme();
updateTheme('light');
// Output: <div>Current theme: light</div>
return <div>Current theme: {theme}</div>;
}
What are the pros of the approach:
- No need to set up a hook somewhere up the tree before children can use it (including test environments);
- The render structure is cleaner, meaning no more confusing arrow-shaped structure built out of your contexts;
- State is synchronized between tabs.
Conclusion
React.createContext() was a powerful tool some time ago for sure, but hooks provide a more controlled and reliable way to manage the global state of your app if properly implemented in conjunction with the use-app-events
package.
Posted on September 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.