DEV Community

Cover image for React.js ~use() for Context~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React.js ~use() for Context~

use() can also read Context, and this is where it breaks a rule that every other hook follows.

Every React hook must be called at the top level of a component, never inside conditions, loops, or early returns. use() is the exception. It can be called conditionally:

function Greeting({ showFormal }: { showFormal: boolean }) {
  if (showFormal) {
    const { locale } = use(I18nContext);
    return <p>{locale === "de" ? "Guten Tag" : "Good day"}</p>;
  }
  return <p>Hey!</p>;
}
Enter fullscreen mode Exit fullscreen mode

With useContext, this code would violate the rules of hooks. With use() lets you skip reading it entirely when the condition is false. With useContext, the component subscribes to that context unconditionally, even when it doesn't need the value.

Top comments (0)