import React, { createContext } from "react";
import React, { useContext } from "react";
Example:
import React, { useState, createContext } from "react";
export const BookContext = createContext();
/* Provider: Holds information & passes it
down to all the different
components that we want to. */
export const BookProvider = props => {
const [books, setBooks] = useState([
{
name: "The Power of Now",
price: "$10.00",
id: 1234
},
{
name: "Becoming Michelle Obama",
price: "$11.89",
id: 2345
},
{
name: "Heart Sutra",
price: "$12.79",
id: 3456
}
]);
{
/* Render all the child components -
<BookContext.Provider>
gives these components access to the
Book provider; whatever is wrapped
in between the context has access to the
data above. */
}
return (
<>
<BookContext.Provider value={[books, setBooks]}>
{props.children}
</BookContext.Provider>
</>
);
};
In App.js, wrap the provider around the components so they will have access to the context.
import React from "react";
import "./App.css";
import Nav from "./Nav";
import BookList from "./BookList";
import { BookProvider } from "./BookContext";
import AddBook from "./AddBook";
function App() {
return (
/* All of the components now have access to the
Book BookProvider, now that they are wrapped in it. */
<BookProvider>
<div className="App">
<Nav />
<AddBook />
<BookList />
</div>
</BookProvider>
);
}
export default App;
This component shows the number of books there are in the array of objects. It needs access to that data to get that info.
import React, { useContext } from "react";
import { BookContext } from "./BookContext";
const Nav = () => {
const [books, setBooks] = useContext(BookContext);
return (
<div className="nav">
<h1>React Bookstore</h1>
<h1># in Cart: {books.length} </h1>
</div>
);
};
export default Nav;
A context is a component that holds/provides data; it holds the state. So, the state is basically set globally. Once you wrap the provider around the components, now the they can simply hook in and get access to the state to change it. This avoids the need to pass props around especially in larger applications.