You are currently viewing Best Way to Understand the Context in React Functional Component

Best Way to Understand the Context in React Functional Component

React Context Functional Component

In React we cannot directly pass data from a parent component to a child component using props, we can only pass according to the order of file navigation like this (parent > intermediate > child). It is called props drilling. When passing such data, the lines of codes and render time will increase, so we can use react context to overcome this problem. We can directly access the data in the parent component to the child or subchild components using context. By using this context feature, we don’t need to pass props data to each component. So, In this article, we’ll see what isĀ  React context in functional component and how to use it.

What is the context?

Context is used to share data and access across components in a React application, regardless of their position in the component tree. If you create a context in a parent component, you can directly access the context data in all child components. This facilitates the flow of data without the need to send props through the hierarchy of intermediate components. To create context, we need to use createContext function from React.

Using React Context in Functional Components

Functional Components have become popular in React because of their simplicity and readability. Before introducing the hooks feature in the functional component, it was purely presentational and lacked the ability to manage the state. However, with the introduction of Hooks, we can now manage state in functional components with fewer lines of code than a class component. So we have to use the useContext hook to access the data provided by the context.

How to create context?

Follow the below steps to create context easily:

    1. To create a new context, we have to import and use the createContext function from React. This function returns two components – a Provider and a Consumer. In most cases, you’ll primarily interact with the Provider, which supplies the data to its descendants.
      import React, { createContext, useState } from 'react';
      
      const MyContext = createContext();

Here, we’ve created a new Context object named MyContext

    1. Next, we’ve to create a provider in the return method of the component “ParentComponent“. The Provider component is obtained from the MyContext object. In the value attribute of the context provider, you should mention any data i.e. variable, state, function that you want to pass to other components. And inside the context provider, you have to mention the name of the component to which you want to pass the data. Here, the ChildComponent is rendered as a child of the MyContext.Provider. Since ChildComponent is within the Provider’s scope, it will have access to the contextValue provided by MyContext.Provider.
      const ParentComponent = () => {
        const contextValue = "Hello from the Context";
      
        return (
          <MyContext.Provider value={contextValue}>
            <ChildComponent />
          </MyContext.Provider>
        );

3. Create a ChildComponent to access the context data. We can access the context provider data by using the useContext hook in the functional component.

import React, { useContext } from 'react';

const ChildComponent = () => {
  const contextValue = useContext(MyContext);

  return <div>{contextValue}</div>; // Output: "Hello from the Context"
};

Note: When you use the context function you must give the same variable name as the context provider value attribute. In the above example, Since we have passed data in the variable name “contextValue” in the context provider value attribute, so we have given the same name while using useContext in the child component.

READ ALSO  Is Learning React Query Worth it for Beginners?

Examples of using context

You can also pass state in a context like:

import React, { createContext, useContext, useState } from 'react';

const MyContext = createContext();

const ParentComponent = () => {
  const [count, setCount] = useState(0);

  return (
    <MyContext.Provider value={{ count, setCount }}>
      <ChildComponent />
    </MyContext.Provider>
  );
};

const ChildComponent = () => {
  const { count, setCount } = useContext(MyContext);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

Here we have created both parent and child components in one file for your understanding. The context provider provides the initial state “count” and updated state “setCount“, the initial state is ‘0’. So, the child component accesses the “count” and “setCount” state by useContext() function. If this code is rendered, the initial state value “0” will be incremented by 1 when the button is clicked.

Here’s an example to use multiple contexts in one context file.

import React, { createContext, useContext } from 'react';

const ThemeContext = createContext();
const LanguageContext = createContext();

const App = () => {
  const theme = "dark";
  const language = "en";

  return (
    <ThemeContext.Provider value={theme}>
      <LanguageContext.Provider value={language}>
        <Toolbar />
      </LanguageContext.Provider>
    </ThemeContext.Provider>
  );
};

const Toolbar = () => {
  const theme = useContext(ThemeContext);
  const language = useContext(LanguageContext);

  return (
    <div>
      <p>Theme: {theme}</p>
      <p>Language: {language}</p>
    </div>
  );
};

Output:

Theme : dark
Language: en

In this above example, we have created two contexts in the App component using “createContext()” function. Then we created a separate context provider with value attribute, inside the provider we’ve mentioned only one component called <Toolbar/>. Finally, we’ve created the Toolbar component and accessed the data “theme” and “language” using “useContext” function.

Conclusion

React Context provides an elegant solution for managing state in functional components, making it easier to share data between multiple components without resorting to prop drilling.

Leave a Reply