DEV Community

Cover image for React Explained: Mastering the useContext Hook
Prashant Kumar Singh
Prashant Kumar Singh

Posted on

React Explained: Mastering the useContext Hook

Welcome🎉, fellow React adventurers, to a whimsical blog where we embark on a hilarious journey through the enchanted land of the useContext hook! 🧙‍♂️✨

Are you ready? Let’s conjure some React awesomeness! 🚀💫

Imagine that you are planning a birthday celebration with a variety of entertainment options, such as face painting 🎨, balloon animals 🎈, and a magic performance 🎩.

For example, face paint is needed for face painting, balloons are needed for balloon twirling, and magic tricks are needed for the magic show. 🎂🎉

Let’s say a friend of yours is willing to assist with the face painting activity. In order to complete the work successfully, they must have access to the face paint supplies. 🖌️

One technique to get the face paint supplies to your friend is to pass them from person to person until they get to your friend. However, if there are many individuals engaged and the party is large, this can be time-consuming and inefficient. ⏰⛔

Instead, a central supply station where all the required supplies are housed can be established. Then, your companion can start face painting by going straight to the supply depot, and picking up the necessary materials. 🚚🎨

This eliminates the need for your friend to rely on third parties to deliver them the materials. 🙅‍♂️🚫

The useContext hook in React accomplishes a similar task. Components can access shared data or state without having to transmit it through a hierarchy of parent and child components thanks to this feature. 🔄🔗

The central supply station serves as the React context in our case. It contains shared information like the face paint supplies. Your friend (the component) can directly access and use the face paint supplies from the context by using the useContext hook. 🏰✨

Prop drilling, which is like passing the face paint supplies from person to person, is avoided by employing the useContext hook. The code is cleaner and more effective when the component can directly get the necessary resources from the context. 🧹🧙‍♀️

I’ve got some enchanting code examples up my sleeve to guide you through this magical adventure! Let’s dive in and unveil the secrets of the useContext hook together.

1. Prop Drilling

Prop drilling involves passing props from one component to another, even if the intermediate components don’t actually need those props.

// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const supplies = {
    facePaint: 'red, blue, green',
    balloons: 'red, yellow, blue',
    magicTricks: 'rabbit, cards, wand',
  };

  return <ChildComponent supplies={supplies} />;
};

export default ParentComponent;

// ChildComponent.js
import React from 'react';
import GrandchildComponent from './GrandchildComponent';

const ChildComponent = ({ supplies }) => {
  return <GrandchildComponent supplies={supplies} />;
};

export default ChildComponent;

// GrandchildComponent.js
import React from 'react';

const GrandchildComponent = ({ supplies }) => {
  const facePaintSupplies = supplies.facePaint;
  // ... do something with facePaintSupplies

  return <div>Grandchild Component</div>;
};

export default GrandchildComponent;

Enter fullscreen mode Exit fullscreen mode

In this example, the supplies are passed from the ParentComponent down to the ChildComponent and then to the GrandchildComponent. However, if there were more levels of components or if the supplies were not needed by the ChildComponent itself, it would result in unnecessary prop passing.

Image description

2. useContext Hook (Context API)

The useContext hook, along with the Context API, provides a more efficient way to share data across components without the need for prop drilling.

// SuppliesContext.js
import React, { createContext } from 'react';

const SuppliesContext = createContext();

export default SuppliesContext;

// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
import SuppliesContext from './SuppliesContext';

const ParentComponent = () => {
  const supplies = {
    facePaint: 'red, blue, green',
    balloons: 'red, yellow, blue',
    magicTricks: 'rabbit, cards, wand',
  };

  return (
    <SuppliesContext.Provider value={supplies}>
      <ChildComponent />
    </SuppliesContext.Provider>
  );
};

export default ParentComponent;

// ChildComponent.js
import React from 'react';
import GrandchildComponent from './GrandchildComponent';

const ChildComponent = () => {
  return <GrandchildComponent />;
};

export default ChildComponent;

// GrandchildComponent.js
import React, { useContext } from 'react';
import SuppliesContext from './SuppliesContext';

const GrandchildComponent = () => {
  const supplies = useContext(SuppliesContext);
  const facePaintSupplies = supplies.facePaint;
  // ... do something with facePaintSupplies

  return <div>Grandchild Component</div>;
};

export default GrandchildComponent;
Enter fullscreen mode Exit fullscreen mode

In this example, the supplies are wrapped within the SuppliesContext.Provider in the ParentComponent. The ChildComponent and GrandchildComponent access the supplies using the useContext hook and SuppliesContext. This eliminates the need for prop drilling and allows components to directly access the required supplies from the context.

Image description

So, grab your React wands and dive into the marvelous world of useContext! and I hope you are now ready to create React magic without the hassle of prop drilling. Let’s make all the components shine and bring some joy to your React spells! 🪄💻✨

References:

  • React Documentation: Context
  • React Hooks API Reference: useContext
  • Kent C. Dodds’ Blog: How to Use React Context Effectively
  • Robin Wieruch’s Blog: A Complete Guide to useContext
  • React Explained Article on Medium: Mastering the useContext Hook

Unlock the full potential of useContext and revolutionize the way you handle data sharing in React applications. Let’s create some React magic together!

Oldest comments (2)

Collapse
 
beginarjun profile image
Arjun Sharma

Great example 👍 Loved the way you explained. Keep up the good work 💪

Collapse
 
devprashantt profile image
Prashant Kumar Singh

Thank you arjun✌️