6.useContext - sabinmarcu/jsleague-react-hooks GitHub Wiki

useContext


const CounterContext = 
    createContext({ counter, increment, decrement });

class Counter extends Component {
    static contextType = CounterContext;

    render() {
        const { counter, increment, decrement } =
            this.context;

        return <div>
            <button onClick={increment}>Increment</button>
            <p>Count: {counter}<p> 
            <button onClick={decrement}>Increment</button>
        </div>
    }
}

Let's start off, again, with our counter, in Component format.

Let's assume we've already created a context with our counter, increment and decrement methods, and created a Provider somewhere higher up the chain of command.

Then we'd have to declare it as the only (!!!) context type available to this Component

And then consume it to be used in rendering.

The con here is that there can only be only one context.


const CounterContext = 
    createContext({ counter, increment, decrement });

const Counter = () => (
    
        {({ counter, increment, decrement }) => (
            <div>
                <button onClick={increment}>Increment</button>
                <p>Count: {counter}<p> 
                <button onClick={decrement}>Increment</button>
            </div>
        )}
    
}

Let's take another example, with render props and a Consumer

Then we'd have to render the consumer...

And then use a render prop to retrieve the data, and use it in rendering.

The cons here are that the information cannot be consumed before rendering, at this component's level.


const CounterContext = 
    createContext({ counter, increment, decrement });

const Counter = () => {
    const { counter, increment, decrement } = useContext(CounterContext);
    return (
        <div>
            <button onClick={increment}>Increment</button>
            <p>Count: {counter}<p> 
            <button onClick={decrement}>Increment</button>
        </div>
    );
}

And finally, what we've been waiting for, the hooks variant.

All we have to do is consume the context directly

Pros include having multiple contexts consumed in the same place, and a lot less code to write for one thing.

Cons: ???


useContext - Takeaways

  • Can consume N contexts, before rendering
  • Can be used in conjunction with other use hooks
⚠️ **GitHub.com Fallback** ⚠️