useContext and Context API

  • React Context is a way to manage state globally.
import { useState, createContext, useContext } from "react";
 
// you will need it in both the parent as well as child
// hence a good idea is to export it from another file
const UserContext = createContext();
 
 
// wrap root <Parent> component inside <UserContext.Provider>
function App() {
	const [user, setUser] = useState("Jesse Hall");
 
	return (
		<UserContext.Provider value={user}>
	      <Parent />
	    </UserContext.Provider>
    );	
}
 
// retrieve information in any subchild of root <Parent> component
function SubChild() {
	const user = useContext(UserContext);
	return (
		<>
		  <h1>SubChild Component of Parent</h1>
		  <h2>{`Hello ${user}`}</h2>
		</>
	);
}