ReactJS Hook “useContext”

What is React Hooks?

Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which “hook into” React state and lifecycle features from function components. It does not work inside classes.

When to use Hooks?

If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing function component.

What is Prop Drilling in ReactJS?

Prop drilling refers to the process of sending props from a higher-level component to a lower-level component.

To pass the props down from the topmost component, we must pass props through every function component.

However, prop drilling can become an issue in itself because of its repetitive code. In order to fix this issue, we use the hook “useContext”.


const MyContext = React.createContext(defaultValue);

Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This default value can be helpful for testing components in isolation without wrapping them. Note: passing undefined as a Provider value does not cause consuming components to use defaultValue.


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

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.

The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.

All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. The propagation from Provider to its descendant consumers (including .contextType and useContext) is not subject to the shouldComponentUpdate method, so the consumer is updated even when an ancestor component skips an update.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Luis Castillo

Luis Castillo

Software Engineer / Full-Stack Developer in Ruby, Ruby on Rails, JavaScript, ReactJS, Redux, SQL, HTML5, CSS3