marp: true
Copyright By PowCoder代写 加微信 powcoder
### The “prop-drilling” problem.
“Lifting state” is a great trick.
Sometimes, it introduces a new problem though.
# Demonstration
Pass the props through in the following example
const App = () => {
const [user, setUser] = useState(null);
const Home = () => {
const Header = () => {
const Navigation = () => {
Home
Log out
const LoginDialogTrigger = () => {
// Some stuff to show a button and handle showing
// the dialog on click
onSubmit={() => {
/* Validate that the credentials are right */
setUser(user);
{/* Imagine a typical login form here */}
This is no fun!
– Pain to wire up
– Not easy to move components around
– Makes a big mess
For _app-wide_ data like the current user, it would be cool if this was available anywhere without needing to “prop-drill”
Context is **global state** for your React tree.
# How it works
First, we create a Context, and make it available to the React tree with `
export const UserContext = createContext(null);
const App = () => {
# How it works
Next, we can _consume_ that context anywhere below the Provider with `useContext`.
import { UserContext } from “../App”;
const Profile = () => {
const data = useContext(UserContext);
console.log(data); // { username: ‘Alfalfa’ }
return
;
# Exercises
Update the following components to use context
const App = () => {
const [user, setUser] = useState({ username: “Alfalfa” });
return
const Home = ({ user, setUser }) => {
const Header = ({ user, setUser }) => {
const Navigation = ({ user, setUser }) => {
Home
About
{user && (
const App = () => {
const [dialog, setDialog] = useState(null);
const MainContent = ({ dialog, setDialog }) => {
Home
About
const Dialog = ({ dialog }) => {
if (!dialog) {
return null;
return
;
“`js live=true
const App = () => {
const [count, setCount] = React.useState(0);
const [name, setName] = React.useState(“”);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count – 1);
Playing as: {name}
increment={increment}
decrement={decrement}
name={name}
setName={setName}
const CountDisplay = ({ count }) => {
return
{count} clicks!
;
const Actions = ({ increment, decrement, name, setName }) => {
// NO NEED TO TWEAK ANYTHING BELOW THIS POINT
const Action = ({ onClick, children }) => {
return ;
const TextInput = ({ label, value, setValue }) => {
type=”text”
value={value}
onChange={(ev) => setValue(ev.target.value)}
render(
# Context vs. Props
Should you _always_ reach for context? Is it OK to pass props?
For now, let’s try and use Context liberally. We need the practice.
Once you’re comfortable with it, the choice is yours.
There is no wrong answer. Do whatever is easiest for you!
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com