REACT+Cheat+Sheet+ +ContextAPI
REACT+Cheat+Sheet+ +ContextAPI
This cheat sheet is for the course React 18 Course - Learn React JS the fast way
by Jannick Leismann.
ContextAPI
Use for handling Global state management without prop drilling. Too
much prop drilling complicates code and makes it very hard to maintain. This is where context
can be an advantage because it can share context information or data to multiple components.
Is designed to share data between components without having to pass props down manually at
every level of the component tree.
Create a Context
Use createContext to create a context. This will hold the data to be shared.
MyContext.js
import React, { createContext, useState } from "react";
//Creating a provider
const MyProvider = ({ children }) => {
const [value, setValue] = useState("Hello from context!");
return <MyContext.Provider
value={value}>{children}</MyContext.Provider>;
};
MyComponent.js
import React, { useContext } from "react";
import { MyContext } from "./MyContext";
return <div>{contextValue}</div>;
};
function App() {
return (
<div className="App">
<div className="container">
<MyProvider>
<MyComponent />
</MyProvider>
</div>
</div>
);
}
export default App;