What is a React Context?

About

A Context1) provides a way to pass data through the component tree without having to pass props down manually at every level.

They are part of tree, normally they would encapsulate a sub-tree and would not return a visible react element but if they can't initialize, you can stop the tree building by returning null or an error message.

Example: Translation

If you want to translate your application, you can use a context.

const englishMessages = message => {
  if (message == "hello.world") {
    return "Hello, World!";
  }
  return "Not yet translated";
};

const TranslationContext = React.createContext();

const Greeting = () => {
  const translate = React.useContext(TranslationContext);
  return <div>
          <p>{translate("hello.world")}.</p>
          <p>{translate("hello.you")}.</p>
      </div>;
};

const App = () => (
  <TranslationContext.Provider value={englishMessages}>
    <Greeting />
  </TranslationContext.Provider>
);
  • And render
ReactDOM.render(<App />, document.getElementById('root'));
<div id="root"><!-- called the "root" DOM node because everything inside it will be managed by React DOM --></div>
  • Output:

2)

Utility

How to know if the context is available?

function useInContext() {
  return React.useContext(MyContext) != null;
}





Discover More
React - Dependency Injection

in React (via parent/children) Interface: only via Typescript
React Props Chrome Plugin
React - Props

props is the only object argument passed from a component to another component. Props are similar to State, but is public and not fully controlled by the component. You can also pass arguments to...
React - State

This page is UI State in React. The Local state to a component in react is known as: state. A change of state triggers a render ref. A change of ref value does not triggers a render The global...



Share this page:
Follow us:
Task Runner