In this article, we will look at how to get rid of React.Context in your apps and find a motivation for doing so.
You are probably familiar with React and may have already had experience with React.Context if you landed at this article, but if not, feel free to read it anyway and share with people who might be interested.
Context degrades readability, entangles and restricts the app.
Just take a look at this basic example:
Doesn't look too comprehensible and reliable, does it?
Here are some potential issues when using contexts:
Fun fact: the well-known "promise-hell" looks alike ?♂️
loadClients() .then((client) => { return populate(client) .then((clientPopulated) => { return commit(clientPopulated); }); });
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:Current theme: lightreturnCurrent theme: {theme}; }
What are the pros of the approach:
React.Context 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3