DEV Community

Everton Reis
Everton Reis

Posted on

Introduction to React Context - How to use it simply

Considerations

  • This is an introductory article and presents a way to use the React Context.
  • It is important that you consult the references to better understand the concepts and when it is useful to use them.
  • Using the context API requires at least basic React knowledge (creating reusable components, state manipulation, props...).

What is the Context API?

If we access the React Context documentation we will have the following definition:

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

Basically we have the following - Context provides a way to pass data between components without having to manually pass through all levels.

But what does it mean?

Data in React is usually passed to components via props, from parent to child. If you have components that are nested in a more complex way, it can be tricky to deal with this data passing between components. And that's where the Context API comes in. Simply, instead of accessing, for example, a state directly from the component or passing through props, you can now access that same state globally.

How to use?

For better understanding you can access the code on CodeSandbox

In the example below we will have:

  1. A file containing the entire Context Api configuration
  2. How to retrieve data typed in input into different components
  3. Two components that will be updated with the values entered in the input

Creating User Context

In the context file is where we create a global variable that can be accessed in every application. The context provider is used to involve a parent component and each child that exists in the application.

For this we will create the useContext.js file, which is where the context instance and the variables to be used will be created.

In useContext.js, create the context object by importing and using createContext

import React, { createContext, useState } from "react";

export const MyContext = createContext();

export const UserProvider = ({ children }) => {
  const [name, setName] = useState("");
  const [lastName, setLastName] = useState("");

  return (
    <MyContext.Provider
      value={{
        name,
        setName,
        lastName,
        setLastName
      }}
    >
      {children}
    </MyContext.Provider>
  );
};
Enter fullscreen mode Exit fullscreen mode

Above we export the MyContext that will be used in the child components. useState to maintain the state of the Name and lastName variables, with their corresponding methods.
These data/variables are passed through the provider's value. The provider serves to provide context to child components.

Wrapping the App component with the created context

The index.js file is imported from the UserProvider context file useContext.js. So we're going to wrap the <App/> with the UserProvider like this:

import ReactDOM from "react-dom";
import { UserProvider } from './useContext';

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
   <UserProvider>
     <App />
   </UserProvider>,
   rootElement
);
Enter fullscreen mode Exit fullscreen mode

From that moment on, all the data passed in value in our context file can be accessed in other components.

Using name and lastName data

To use the first and last name data, two components were created ComponentName.js and ComponentLastName.js. In both files it is necessary to import the MyContext from our context file and the useContext hook that will be used to set the context that we will use to access the available data. Staying like this:

nameComponent.js

import React, { useContext } from "react";
import { MyContext } from "./useContext";

const Name = () => {
  const user = useContext(MyContext);

  return (
    <div>
      <h2>
        <strong>Name</strong>: {user.name}
      </h2>
    </div>
  );
};

export default Name;
Enter fullscreen mode Exit fullscreen mode

lastNameComponent.js

import React, { useContext } from "react";
import { MyContext } from "./useContext";

const LastName = () => {
  const user = useContext(MyContext);

  return (
    <div>
      <h2>
        <strong>Last Name</strong>: {user.lastName}
      </h2>
    </div>
  );
};

export default LastName;
Enter fullscreen mode Exit fullscreen mode

Note that, in both components, the code was used:

const user = useContext(MyContext);
Enter fullscreen mode Exit fullscreen mode

The user const will be responsible so that we can access the global variables of our context.

Updating context data

In the App.js file, we import the MyContext and using the useContext hook we will consume the data from our context. With the setName and setLastName methods retrieved from the context, we call onChange on the respective inputs so that the data is updated with each character typed by the user. Staying like this:

import React, { useContext } from "react";
import { MyContext } from "./useContext";

import Name from "./ComponentName";
import LastName from "./ComponentLastName";

import "./styles.css";

export default function App() {
  const user = useContext(MyContext);

  return (
    <div className="App">
      <div>
        <div>
          <label className="label">Name: </label>
          <input
       onChange={(event) =>
       user.setName(event.target.value)} />
        </div>
        <div>
          <label>Last Name: </label>
          <input
       onChange={(event) =>
       user.setLastName(event.target.value)}
          />
        </div>
      </div>
      <Name />
      <LastName />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Thus, every time a change is detected in one of the inputs, it will trigger the corresponding method, which changes the value in the context, thus updating the information in ComponentName.js and ComponentName.js.

Conclusion

In this article, we use React Context to create global variables and use them in components without having to use props.

References

React Context Doc

Connect with me

GitHub

Top comments (1)

Collapse
 
king11 profile image
Lakshya Singh

Thanks for this nicely explained :)