React from Newbie Perspective — useContext

Jiri Beck
CodeX
Published in
2 min readJun 3, 2021

For me context is the key — from that comes the understanding of everything.

— Kenneth Noland

Photo by Pakata Goh on Unsplash

What is Context in React?

When building React application, we often went into situation, when we need to get data from parent to child, but sometimes, it is not direct child, but descendant deep in component tree, so we can pass data through lots of components, that don’t even need this data (aka props drilling), or we need to use these data in so many components, that it doesn’t make sense pass data as props to all of these components. All of these manual passing data can be done with different approach. We can use Redux, when our app needs robust solution, or we can use built-in React Context. With Context, we can share values without props drilling or any other manual passing.

Context serves to sharing “global” data like preferred language, UI theme or authenticated user or his/her app settings.

But Context itself is not self-saving. We may use simpler way, when there is no need for “global” values, like component composition, but it is not part of this article.

How does React Context looks like?

React.createContext

const MyContext = React.createContext(defaultValue);

As method name says, it creates new Context object. Context object consist of two properties that are meant to communicate with each other, Provider and Consumer. We can even use object destructuring and create new Context as:

const { Provider, Consumer } = React.createContext(defaultValue);

Provider

<MyContext.Provider value={/* some value */}>

Consumer

function Func() {   return (
<>
<MyContext.Consumer>
{value && <div>This is current {value}.</div>}
</MyContext.Consumer>
</>
);
}

So what about useContext?

As we see, Context is already fully functional, but in more complex application, we may need use more than one Context to render only one component, which will lead into nesting of Consumers. React Hook useContext comes to make this code cleaner and allow us to not use Consumer as wrapper to get to needed value, but allow us to get values directly from Context.

import React, { useContext } from 'react';function Func() {
const value = useContext(MyContext);
return (
<>
{value && <div>This is current {value}.</div>}
</>
);
}

Conclusion

Context itself is really powerful React feature, that works out of the box with basic React installation. Main purpose is to provide values and parameters, that needs to be shared across our application and simplifies its distribution.

React Hook useContext give us next level of simplification, especially in case of using more than one Context values in one component.

--

--

Jiri Beck
CodeX
Writer for

Wannabe programmer from Czech republic, who loves sport, challenges and Chihuahuas