Just Learn Code

Managing Global State in React with Context API

Introduction to React Context API

As a React developer, you’ve probably come across the challenge of sharing data across different components. Passing props through the component tree can become messy and tedious, especially when dealing with deeply nested components.

This is where the React Context API comes in handy.

What is React Context API?

React Context API is a way to manage global state in a React application. It allows you to share data between components without having to pass props through all the intermediate components.

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

Benefits of using React Context API

1. Data Sharing – With React Context API, you can share data across components without the need to pass props down the component tree.

2. Component tree – This API solves the problem of having to pass props through numerous components in the component tree.

This makes the code more organized and easier to understand. 3.

Props – Since React Context API allows you to avoid using props, your code will be cleaner, shorter, and less prone to errors.

Creating Context with React.createContext()

Now that weve covered what React Context API is and its benefits, let’s dive into creating context with React.createContext().

Creating context with React.createContext()

React.createContext() method creates a new context object. The context object comes with two components, a provider and a consumer.

The provider component provides the context to the rest of your application, while the consumer component retrieves the context. Example:

const MyContext = React.createContext();

Assigning default data into React.createContext()

In some cases, it can be helpful to add default data that will be used if there is no matching provider component.

You can do this by passing the default data as a parameter to create context method. Example:

const MyContext = React.createContext(‘default value’);

Now, any component that renders without a matching provider component will use the default value provided.

Conclusion

React Context API is a powerful tool that allows developers to manage state in React with ease. With it, you can avoid the hassle of passing props through numerous components and keep your code cleaner and more organized.

React.createContext() method provides a way to create context objects that you can then use to pass data around your application. The addition of default data gives you even more control over how your context is used.

Once you get used to working with context, you’ll be able to create much more manageable and scalable React applications.

Providing Context

Now that we understand the basics of React Context API and how to create context with React.createContext(), let’s explore how to provide and consume the context.

Obtaining value from state to provide into context

To provide a value to your context, you first have to obtain it from your component’s state. The value can be any data type including strings, numbers, objects, and arrays.

Example:

“`

import React, { useState } from ‘react’;

export const MyContext = React.createContext();

function MyApp() {

const [myValue, setMyValue] = useState(‘Hello World!’);

return (

)

}

“`

In the example above, we use the useState hook to set the initial value of the myValue state to “Hello World!” The context is then created with this value.

Wrapping React component with Provider component

After obtaining the value of your context, you’ll need to wrap your component with the Provider component. This provides the context value to all of the child components wrapped inside it.

Example:

“`

const MyContext = React.createContext(defaultValue);

{/* child components */}

“`

In the example above, we create the MyContext object with a default value, and then wrap our child components with the Provider component. The value property of the Provider component is where you pass in the actual value that you want to provide to your components.

Accessing value of context with useContext hook

To access the value of your context inside a functional component, you’ll need to use the useContext hook. Example:

“`

import { useContext } from ‘react’;

import { MyContext } from ‘./MyContext’;

function MyComponent() {

const { myValue, setMyValue } = useContext(MyContext);

return (/* some JSX */)

}

“`

In the example above, we import the useContext hook and the MyContext object and extract the values we need from the context using object destructuring.

The useContext hook takes the MyContext object as an argument and returns the values we want to use.

Consuming Context in Function Components

Grabbing value of context with useContext hook

Now that we know how to provide a value to our context, let’s explore how to consume it in function components. We can use the useContext hook to easily retrieve the context value.

Example:

“`

import React, { useContext } from ‘react’;

import { MyContext } from ‘./MyContext’;

function MyComponent() {

const { myValue } = useContext(MyContext);

return (

{myValue}

)

}

“`

In the example above, we import the MyContext object and the useContext hook. We then extract the value of myValue from the context using object destructuring.

Changing context value with state

If you want to update the value of your context, you’ll need to use state. You cannot directly update the context value as it is immutable.

Instead, you’ll have to change the value of a state variable and then update the context value with that state variable. Example:

“`

import React, { useContext, useState } from ‘react’;

import { MyContext } from ‘./MyContext’;

function MyComponent() {

const { myValue, setMyValue } = useContext(MyContext);

const [newState, setNewState] = useState(”);

const handleClick = () => {

setNewState(‘New Value’);

setMyValue(newState);

}

return (

<>

{myValue}

)

}

“`

In the example above, we import the MyContext object, useContext hook, and useState hook.

We use the useState hook to create a new state variable called newState. We then create a handleClick function that sets the value of newState to “New Value”, and then updates the context value using setMyValue.

Conclusion

React Context API is a powerful tool you can use to globally manage state in your React application. By providing and consuming the context, we can pass data between a tree of components without having to rely on traditional props.

To provide a value to your context, you first have to obtain it from your component’s state, wrap your components with the Provider component, and then access the value of your context using the useContext hook. To change the value of your context, we need to use state variables and update the context value with that state variable.

By using these methods effectively, we can build scalable and reusable components that share data freely across your application.

Consuming Context in Class Components

While the useContext hook is beneficial for functional components, class components can consume the Context API in different ways. Let’s explore two different ways: via the Context.Consumer component and the contextType property.

Using Context.Consumer component

The Context.Consumer component is a way to consume the Context API inside a class component. It allows you to pass a function as its child to retrieve the value of the context.

Example:

“`

import React from ‘react’;

import MyContext from ‘./MyContext’;

class MyClass extends React.Component {

render() {

return (

{({ myValue }) =>

{myValue}

}

)

}

}

“`

In the example above, we import the MyContext object and wrap it in the Context.Consumer component. We pass a function as its child that receives the value of the context, specifically the myValue property.

This function then returns the JSX that you want to render.

Using contextType property to consume context

The contextType property is a cleaner and more concise way to consume the context value inside a class component. Example:

“`

import React from ‘react’;

import MyContext from ‘./MyContext’;

class MyClass extends React.Component {

static contextType = MyContext;

render() {

const { myValue } = this.context;

return (

{myValue}

)

}

}

“`

In the example above, `static contextType = MyContext` is used to indicate to the component that it expects to consume the MyContext object.

This makes the value of the context available via `this.context`. We then extract the value of `myValue` from `this.context` and render it in our JSX.

Separating Context from Components

Passing context value into multiple components

One of the great things about Context API is that it allows us to provide values to multiple components at once, making it easier to maintain the state of your entire application.

Example:

“`

import React from ‘react’;

import MyContext from ‘./MyContext’;

function Header() {

return (

{({ myValue }) =>

{myValue}

}

)

}

function Content() {

return (

{({ myValue }) =>

{myValue}

}

)

}

class App extends React.Component {

render() {

return (

)

}

}

“`

In the example above, we create two separate functional components, `Header` and `Content`.

Both components wrap the `MyContext.Consumer` component that receives the value of `myValue` from the context and renders it in a heading or paragraph. The `App` class component wraps both functional components in the `MyContext.Provider` component to provide a value to multiple components at once.

Referencing context object in function and class components

Sometimes, you might need to reference the context object in your function or class components.

In functional components, you can use `MyContext.displayName` to reference a named context object.

Example:

“`

import React, { useContext } from ‘react’;

import MyContext from ‘./MyContext’;

function MyComponent() {

MyComponent.displayName = ‘MyDisplayName’;

const { myValue } = useContext(MyContext);

return (

{myValue}

)

}

“`

In the example above, we set the displayName property of MyComponent to “MyDisplayName”. This allows us to reference the named context object in our unit tests.

This is particularly useful when the context is a mock value when running tests. In class components, you can call `React.createContext()` directly on the class.

Example:

“`

import React from ‘react’;

class MyClass extends React.Component {

static contextType = React.createContext({ myValue: ” });

render() {

const { myValue } = this.context;

return (

{myValue}

)

}

}

“`

In the example above, we use `React.createContext({ myValue: ” })` directly on the class definition. This allows us to reference the named context object as `this.context` in the class component.

Conclusion

With the Context API, React developers have a more efficient way to manage shared state in an application. The Context API allows for a dual-way data flow that helps create maintainable React components.

By using Context.Consumer and contextType to consume context in class components, you can access the value of a context and pass data between sibling components without having to drill data through the tree. Separating context from components is also an important aspect of using the Context API.

You can reference the context object in a functional component using `MyContext.displayName`, while for class components, you can call `React.createContext()` directly on the class. React Context API is a powerful way to manage global state in a React application that allows you to share data between components without having to pass props through all the intermediate components.

In this article, we have explored the basics of React Context API, covered how to create and provide context using React.createContext(), and how to consume it using useContext, Context.Consumer, and the contextType property. Additionally, we have talked about separating context from components, including passing the value of the context into multiple components and referencing the context object in both functional and class components.

Understanding these topics is crucial for creating scalable and maintainable React applications. By leveraging React Context API, developers can handle shared data in a more efficient way that saves time and reduces lines of code.

Popular Posts