Home >Web Front-end >JS Tutorial >Don&#t use React.Context, create hooks.

Don&#t use React.Context, create hooks.

王林
王林Original
2024-09-05 06:44:26755browse

Don

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.


1. Why avoid React.Context?

Context degrades readability, entangles and restricts the app.

Just take a look at this basic example:

98a86725d72d98f2b9cabc482365e7f8
  4b90a298546767af0dfbf93180d488e9
    9ccdbad4d7cf2a5ab2f30697c3e282f0
      805c6193b8bd78f920c172a82a0e8e47
        5b13746435d164e45e11fb6d2c565337
      98e42f95a9cd80104723307a01d2a42d
    37fe62713bcc433be054e66f06fcb3ad
  30fcab49531d609f912afed89b90ce7e
f27e91231f5585982d1354585706ae4a

Doesn't look too comprehensible and reliable, does it?

Here are some potential issues when using contexts:

  1. The more contexts used, the less readable and controllable your app becomes;
  2. Sometimes nested contexts require a correct order to work, which makes your app difficult to maintain;
  3. Some contexts should be re-used during the setup of a test environment to keep working properly;
  4. 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.Context?

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: dc6dce4a544fdca2df29d5ac0ea9906bCurrent theme: light16b28748ea4df4d9c2150843fecfba68
  return dc6dce4a544fdca2df29d5ac0ea9906bCurrent theme: {theme}16b28748ea4df4d9c2150843fecfba68;
}

What are the pros of the approach:

  1. No need to set up a hook somewhere up the tree before children can use it (including test environments);
  2. The render structure is cleaner, meaning no more confusing arrow-shaped structure built out of your contexts;
  3. State is synchronized between tabs.

Conclusion

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.

The above is the detailed content of Don&#t use React.Context, create hooks.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn