React Context API

Context gives us a way to pass data through the component tree without having to pass props down manually at every level.

Pre Hooks

API:

const CountContext = React.createContext();
function Component() {
return (
<CountContext.Provider value={0}>
<CountContext.Customer>
{value => <p>{value}</p>}
</CountContext.Customer>
</CountContext.Provider>
)
}

The provider component will get the value as a prompt, an then any child / grandchild / grandgrandchild component will get value as the props. We can get any value we pass in to the provider anywhere. However, the counter does not have any state management, thus, we still need to use state for the value we pass in to the provider.

Post Hooks

const CountContext = React.createContext();
// Provider Component
const value = {valuesInside: [{id:1, value:4},{id:2, value:3},{id:3, value:3}], onIncrement, onDecrement};
return (
<CountContext.Provider value={value}>{this.props.children}</CountContext.Provider>
)
// Customer Component
const { valueInside } = useContext(CountContext);

Benefits and Drawbacks:

However, when we use context API, there are some drawbacks:

  1. We lose light performance optimization when moving to Context API. It is because React no longer knows which component exactly changes. E.g, we got 3 values in the counter, each rendered in a different component, however, when one of the value changes, all three values will also change. However, this problem may not be very critical as React itself is fast.

  2. We lose the ability to test some components. Previously, we could pass in test values as props, now it's hooked inside the context API. To handle it, we could use a Test Context. Another way to handle it is to create a container component acting as a higher order component which handle context and pass it into the presentational component that's gonna get the values as props. This is very common to do when we use Redux to separate those two.

The good thing about context API:

  1. We can confidently move around components, without worrying about whether the components got the data they needed.

  2. It is easy to maintain. It separates the presentation from the logic.