Most of our components will directly fetch the data that they and their children need. In other cases, our app has some API endpoint with data that is used by several components throughout the application. To share global data like this, you can use the React context API. As the name suggests, components that are rendered within a context are able to access the data provided by the context.
Let's build an example to help clarify what this means and how it relates to Hooks. Here is the UserContext context and the UserProvider component:
import React, { createContext, useState, useEffect } from "react";
export const UserContext = createContext();
function fetchUser() {
return new Promise(resolve => {
setTimeout(() => {
resolve({ id: 1, name: "Adam" });
}, 1000);
});
}
export function UserProvider({ children }) {
const [user, setUser] = useState({ name: "..." });
useEffect(() => {
fetchUser().then(user => ...