React Context

What is React Context ?

In React, “context” refers to a way of sharing values, such as a user authenticated state, theme, or language preference, between components without having to pass props down the component tree manually.

Context is created using the React.createContext() method, which returns an object with a Provider and a Consumer component. The Provider component is used at the top level of the component tree, and it allows you to set the value for the context. The Consumer component is used within child components and it allows you to access the value of the context.

For example, if you have a theme context, the top-level component could be the Provider that sets the theme, and all child components could use the Consumer to access the theme value and update their styles accordingly. This way, you do not have to pass the theme prop down through every level of the component tree.

It’s important to notice that context is not recommended for passing data that changes frequently or for passing down callbacks. This should be done through props.

Here’s an example of how to use React Context to share a theme between components:

1. Create the context:

const ThemeContext = React.createContext('light');

2. Use the Provider component to set the theme at the top level of the component tree:

function App() {
  const [theme, setTheme] = useState('light');
  
  return (
    <ThemeContext.Provider value={theme}>
      <Header setTheme={setTheme} />
      <MainContent />
      <Footer />
    </ThemeContext.Provider>
  );
}

3. Use the Consumer component within child components to access the theme value and update their styles accordingly:

function Header({ setTheme }) {
  return (
    <header>
      <ThemeContext.Consumer>
        {theme => (
          <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
            {theme === 'light' ? 'Switch to dark mode' : 'Switch to light mode'}
          </button>
        )}
      </ThemeContext.Consumer>
    </header>
  );
}
function MainContent() {
  return (
    <main>
      <ThemeContext.Consumer>
        {theme => (
          <div className={`${theme}-mode`}>
            <h1>Welcome to my website</h1>
            <p>This is the main content</p>
          </div>
        )}
      </ThemeContext.Consumer>
    </main>
  );
}

In this example, the App component is the top-level component, which sets the theme state and provides it to the context. The Header and MainContent components are child components that use the Consumer component to access the theme value from the context and update their styles accordingly.

It’s important to notice that the context can also use a useContext hook to access the context value, this way the code is more readable.

const theme = useContext(ThemeContext);

There are two types of React context:

  1. Class context : This is the original context API that was first introduced in React. It uses a combination of React’s context and Provider components to create and provide context to other components. This type of context is created using React.createContext() method, and it is accessed in a component using static contextType or this.context in class components.
  2. Hooks context : This is the new context API that was introduced in React 16.8. It uses the useContext() hook to access context in functional components. This type of context is created using the same React.createContext() method, and it is accessed in a component using useContext(MyContext) hook.

Both types of context are used to share state and functionality between components, but the Hooks context API is more flexible and powerful because it can be used in functional components and also allows for more fine-grained control over when a component re-renders in response to context changes.

When to use React Context ?

React’s context API should be used in situations where you need to pass props down through multiple levels of a component tree without having to pass them through every component manually. This can make component code simpler and more modular, and also improve performance by reducing the number of re-renders that need to happen.

Advantages of React Context

  1. Sharing global state: Context can be used to store and update global state, such as user authentication information or theme preferences, that needs to be accessed by multiple components throughout an application.
  2. Managing complex component hierarchies: Context can be used to pass data down through a component tree without having to pass props through every level. This can make it easier to manage large and complex component hierarchies.
  3. Improving performance: By reducing the number of props that need to be passed down through a component tree, context can help to improve the performance of an application by reducing the number of re-renders that need to happen.
  4. Building reusable components: Context can be used to share functionality between components that are not directly related in the component tree, making it a useful tool for building reusable components.
  5. Handling cross-cutting concerns: Context can be used to handle cross-cutting concerns, such as error handling, that need to be handled in multiple parts of an application, so that these concerns can be managed in one central place.