React Hooks review #3: useContext

This is chapter three of the React Hooks series. The goal is simple: summarize all the eleven official React hooks:

useContext

Accepts a context object and returns the current context value for that context.

To appreciate this hook you need to be familiar with the react context and the allegiant way they simplified the use of it without wrapping the component with a consumer. Each time the context changes, the component using useContext will re-render.

Syntax:

const value = useContext(MyContext);

Simple example:

// Some structured object
const mySuperHero = {
    superAmeba: {
        name: "Amebaba",
        superPower: "do nothing"
    },
    superSlug: {
        name: "Slugestine",
        superPower: "slow motion"
    },
    superPanda: {
        name: "Pandemic",
        superPower: "look at you with its sad face"
    }
}

// Initiate the Context
const SuperHeroContext = React.createContext(mySuperHero.superPanda)

// The wrapper with the context
const App = () =>{
    const [hero,setHero] = React.useState(mySuperHero.superSlug);

    return <SuperHeroContext.Provider value={hero}>
        <button onClick={()=>setHero(mySuperHero.superAmeba)}>Super Ameba</button>
        <button onClick={()=>setHero(mySuperHero.superPanda)}>Super Panda</button>
        <button onClick={()=>setHero(mySuperHero.superSlug)}>Super Slug</button>
        <Arena />
    </SuperHeroContext.Provider>
}

// The component
const Arena = ()=>{
    const superHero = React.useContext(SuperHeroContext)
    return <div>
        <p>Welcome: {superHero.name}. </p>
        <p>The only one that can {superHero.superPower}</p>
    </div>
}

But since this one was a short post, here is a video of O mighty Super-Slug

Next up, the first of the seven additional Hooks: useReducer.