34. What are the differences between using useContext hook and the use API for accessing context values in React?
medium

In React, there are two primary ways to access Context values: through the useContext hook and the use API. While both methods achieve similar results, they differ in their usage and flexibility.


The useContext hook is a part of the standard React API for accessing context values. To use it, you must call it at the top level of your component tree. This means that if you try to use it inside conditionals or loops like if statements or for loops, it won't work as expected.

import { useContext } from 'react';

function Button() {
  const theme = useContext(ThemeContext);
  // ...
}

The use API is an alternative provided by React for accessing context values. Unlike useContext, the use API can be called inside conditionals and loops like if statements or for loops, making it more flexible.

import { use } from 'react';

function Button() {
  const theme = use(ThemeContext);
  // ...
}

Key Differences

  • Flexibility: The use API is more flexible because it can be called inside conditionals and loops, whereas useContext must be used at the top level of your component tree.

Example Usage

Consider the following example where we use both useContext and the use API inside an if statement:

import { useContext } from 'react';
import { use } from 'react';

function HorizontalRule({ show }) {
  if (show) {
    // Using useContext will fail because it's called inside a conditional
    const theme = useContext(ThemeContext);

    // But using the use API works fine
    const themeFromUseAPI = use(ThemeContext);

    return <hr className={themeFromUseAPI} />;
  }
  return false;
}

Common Pitfall

Like useContext, use(context) always looks for the closest context provider above the component that calls it. It searches upwards and does not consider context providers in the component from which you’re calling use(context).


Conclusion

In summary, while both useContext and the use API can be used to access Context values in React, the use API offers more flexibility because it can be called inside conditionals and loops. The useContext hook is still a powerful tool for accessing context, but its limitations make the use API a better choice when working with complex component trees or dynamic conditional logic.