useContext

In notebook:
FrontEndMasters Intermediate React
Created at:
2019-06-23
Updated:
2019-08-15
Tags:
React libraries JavaScript

https://frontendmasters.com/courses/intermediate-react-v2/usecontext/

useContext

Context is for applicaton level state and to avoid props drilling (passing down props many levels deep, and "somehow", passing them up again).

  //****Context.js****


import React, { useState, useContext, createContext } from "react";

// this is just a fake object
// to let people know the shape of the object
const UserContext = createContext([
  {
    firstName: "Bob",
    lastName: "Bobberson",
    suffix: 1,
    email: "bobbobberson@example.com"
  },
  // the updater function o
  // "identity" function 
  // continue reading at `ContextComponent`
  obj => obj
]);

const LevelFive = () => {
 // **** 4. have access to the context here!.  ↴
  const [user, setUser] = useContext(UserContext);

  return (
    <div>
      <h5>{`${user.firstName} ${user.lastName} the ${user.suffix} born`}</h5>
      <button
       // **** 5. the increment function works here too.  ↴
       // using the hook, and context
       // which is on a grand-grand-grand parent...
        onClick={() => {
          setUser(Object.assign({}, user, { suffix: user.suffix + 1 }));
        }}
      >
        Increment
      </button>
    </div>
  );
};

const LevelFour = () => (
  <div>
    <h4>fourth level</h4>
    <LevelFive />
  </div>
);

const LevelThree = () => (
  <div>
    <h3>third level</h3>
    <LevelFour />
  </div>
);

 // **** 3. no context used here, but see step 3.  ↴
const LevelTwo = () => (
  <div>
    <h2>second level</h2>
    <LevelThree />
  </div>
);

// this is the top level component 
const ContextComponent = () => {
// **** 1. create the hook.  ↴
  const userState = useState({
    firstName: "James",
    lastName: "Jameson",
    suffix: 1,
    email: "jamesjameson@example.com"
  });

  return (
   // **** 2. wrapping it in the context.  ↴
    <UserContext.Provider value={userState}>
      <h1>first level</h1>
      <LevelTwo />
    </UserContext.Provider>
  );
};

export default ContextComponent;