Using context
The context API is designed to contain data that is common for a number of components in the application. Data in top-level context can be considered global.

Creating context

The context object will be required to both write and read data in the context. It's best to have it in a separate file.
1
import React from "react";
2
3
export const MessageContext = React.createContext("Hello!")
Copied!
The createContext method takes an optional default value and returns the context object that contains both the provider (write data) and consumer (read data) bits:
1
interface Context<T> {
2
Provider: Provider<T>;
3
Consumer: Consumer<T>;
4
displayName?: string;
5
}
Copied!

Using the context

The easiest way to use context is the useContext hook:
1
import React, { useContext } from "react";
2
import MessageContext from "./message-context";
3
4
const Message: React.FC = () => {
5
const message = useContext(MessageContext);
6
7
return <h1>{message}</h1>;
8
};
9
10
export default Message;
Copied!
Given the Context object created earlier, the useContext hook returns the current context's value.

Providing values

The above code will work without any modifications - it will just show the default value provided when creating the context.
Using the Context.Provider component its possible to provide a different value:
1
import MessageContext from "./message-context";
2
import Message from "./Message";
3
4
function App() {
5
return (
6
<MessageContext.Provider value="Hello, Devmeetings">
7
<Message />
8
</MessageContext.Provider>
9
);
10
}
Copied!

Resources

Last modified 2yr ago