Simple Context API Usage
In React there are many ways of sharing data throughout your application. You can pass data as a prop from a parent component to a child component. You can use a third-party library such as Redux to globally store data in a container of sorts. Another way of sharing data is by utilizing React’s Context API.
The Context API allows your data to be available anywhere you need it inside your application. This is incredibly useful for situations in which multiple components must have access to the same data. You could pass this data down through multiple components until you arrive at the component that needs it. But of course, it is best to avoid prop drilling as it is inefficient and unnecessary. Context API is not a replacement for Redux, but it is sometimes appropriate to integrate Context API instead of Redux for its ease of implementation, reduced lines of code, and avoidance of additional complexity.
There are three primary steps needed to integrate Context API into your application. This is a very simple example but the process is essentially the same for all use cases.
This example is for for accessing a language as a string (such as English or Spanish) throughout an application.
Step 1: Create a Context
You first need to create a new context object. A good practice is to make a new folder inside the /src
directory that holds all of your contexts, like /src/contexts
. Then, create a new file in this new subdirectory, such as LanguageContext.js
. In this new file add the lines below:
import React from ‘react’;
const LanguageContext = React.createContext();
export default LanguageContext
Note: You can specify a default value in the parenthesis, such as ‘Spanish’, but it is not required.
Step: 2: Wire Up Your Component
In the parent component (in which you have the data you want to share), you must wrap the child component(s) that you want to share data with by the newly created Context AND Provider component. This looks something like this:
import React from ‘react’;
import LanguageContext from ‘../contexts/LanguageContext’;
import UserForm from ‘./UserForm’;
If UserForm
is the component (or if UserForm
renders additional components) that we want to share data with, in your return
or render
block for this component, wrap the child component as so:
<LanguageContext.Provider value='Spanish'>
<UserForm />
</LanguageContext.Provider>
By tacking on .Provider
, which is a React component, the UserForm
component will now be subscribed to any context changes that occur. The value
that is passed in is the context.
In this example we are hardcoding ‘Spanish’ as the language, but in a real-world application, you would generally pass in state as the value so that as the language
state changes, all wrapped components have access to the updated value.
Step 3: Use the Context
This is where you actually use the data in the child component(s). At the top of the child component file, import the necessary things:
import React, { useContext } from ‘react’;
import LanguageContext from ‘../contexts/LanguageContext’;
And inside the actual child component, use the context hook by passing in the imported context:
const language = useContext(LanguageContext);
return <div>{language}</div>
Now, the language
variable above is wired up to change whenever the Provider’s value
changes in the parent component. Success!
This was a very simple usage of React’s Context API but the same setup and principle applies for more complex usages. You will most likely pass in state
as the value
in the Provider. You can also pass in setState
as the value
for updating the state. An example of this using hooks would be something like:
const [language, setLanguage] = useState(‘Spanish’);
And in your return
:
<LanguageContext.Provider value={[language, setLanguage]}>
<UserForm />
</LanguageContext.Provider>
This not only provides your deeply nested child components access to the necessary data, but also allows the child components to update the data (state)!
That’s it!