How to use CreateContext() and useContext() in your application.
React lets you build user interfaces out of individual pieces called components. Create your own React components like Thumbnail, LikeButton, and Video. Then combine them into entire screens, pages, and apps.
1. Create a context file, e.g. user-context.js
import { createContext } from "react";
export const UserContext = createContext();
2. Create a root component with context provider.
import { useState } from "react";
import { UserContext } from "./user-context";
import { ComponentDemo1 } from "./component-1";
import { ComponentDemo2 } from "./component-2";
export default function ContextDemo() {
const [ appSettings, setAppSettings ] = useState({ message: "" });
return (
<div>
<h1>Context Demo 1</h1>
<UserContext.Provider value={{ appSettings, setAppSettings }}>
<ComponentDemo1></ComponentDemo1>
<ComponentDemo2></ComponentDemo2>
</UserContext.Provider>
</div>)
}
3. Create components, share and change shared values.
Component #1
import { useContext } from "react";
import { UserContext } from "./user-context";
export function ComponentDemo1() {
const { appSettings, setAppSettings } = useContext(UserContext);
return (
<>
<h2>Component 1</h2>
<p>{JSON.stringify(appSettings)}</p>
</>
)
}
Component #2
import { useContext } from "react";
import { UserContext } from "./user-context";
export function ComponentDemo2() {
const { appSettings, setAppSettings } = useContext(UserContext);
setTimeout(() => {
setAppSettings({ message: "Done" });
}, 1000);
return (
<>
<h2>Component 2</h2>
<p>{JSON.stringify(appSettings)}</p>
</>
)
}