useContext Hook

useContext Hook

Cozy Ride On React useContext Hook ๐ŸŽฃ

ยท

4 min read

๐Ÿ“In our previous article, we learned about two important things: useState and useEffect hooks. ๐Ÿ˜Š

๐ŸŽฏ Today, we're going to learn about another hook called useContext. This hook is quite popular in React programming.

๐Ÿ” Understand How we can do things without using useContext. ๐Ÿค”

To do this without Context, we will need to pass the state as props through each nested component. This is called prop drilling.

import { useState } from "react";

function App() {
  const [user, setUser] = useState("Kushal Das");

  return (
    <>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 user={user} />
    </>
  );
}

function Component2({ user }) {
  return (
    <>
      <h1>Component 2</h1>
      <Component3 user={user} />
    </>
  );
}
function Component3({ user }) {
  return (
    <>
      <h1>Component 3</h1>
      <h2>{`Hello ${user} again!`}</h2>
    </>
  );
}
export default App

๐Ÿ“ค Output:

In this code, we have an App component that manages the user data using the useState hook.

Even though component 2 did not need the state, they had to pass the state along so that it could reach component 3.

The problem in this code is that it's passing the user data as a prop through multiple nested components, which can become cumbersome and repetitive.

๐Ÿ˜… So we saw the problem now To solve this issue we gonna we have to use context.

What is useContext exactly? ๐Ÿค”

The useContext hook is handy when you want to pass data down to multiple nested child components. Instead of sending it through every component along the way, you can define it in the parent component and then use it in the nested component where you need it, without bothering with the middle components. Cool, right? ๐Ÿ˜Ž

Why do we need context Hook? ๐ŸŒฒ

In React, our app is like a tree with different components. One component can be the parent of another. Information usually flows from the parent to the child and so on. If a component is deep down in the tree, the information has to travel through many other components to reach it. ๐Ÿ˜ฎโ€๐Ÿ’จ

To make things easier, some React developers use a library called Redux. It acts like a global storage space for data that can be accessed by any component without going through all the middle components.

But React has its own way to handle global data storage, and that's where useContext comes in. ๐Ÿ˜ƒ

๐Ÿš€ Let's understand how we can use useContext() hook in our program.

๐Ÿ“ฆ Here's an example:

  1. Import React Dependencies:

     import { useState, useContext, createContext } from "react";
    

    We import the necessary dependencies from React, including useState for managing state, useContext for accessing context data, and createContext to create a context for sharing data.

  2. Create a UserContext:

     const UserContext = createContext();
    

    We create a UserContext using the createContext function. This context will be used to share the user data across components.

  3. Define the App Component:

     function App() {
       const [user, setUser] = useState("Kushal Das");
    
       return (
         <UserContext.Provider value={user}>
           <h1>{`Hello ${user}!`}</h1>
           <Component2 />
         </UserContext.Provider>
       );
     }
    
    • In the App component, we initialize a user state variable using useState and set it to Kushal Das.

    • We wrap the content of the App component with a UserContext.Provider. This provider allows child components to access the user value provided as value={user}.

    • We render an <h1> element that displays a greeting with the user's name.

    • We render Component2, which will also have access to the user value.

  4. Define Component2:

     function Component2() {
       const user = useContext(UserContext);
    
       return (
         <>
           <h1>Component 2</h1>
           <Component3 />
         </>
       );
     }
    
    • In Component2, we use the useContext hook to access the user data from the UserContext. This allows us to avoid passing user as a prop explicitly.

    • We render an <h1> element with "Component 2" and then render Component3.

  5. Define Component3:

     function Component3() {
       const user = useContext(UserContext);
       return (
         <>
           <h1>Component 3</h1>
           <h2>{`Hello ${user} again!`}</h2>
         </>
       );
     }
    
    • Component3 is similar to Component2. It also uses the useContext hook to access the user data from UserContext.

    • We render an <h1> element with "Component 3" and an <h2> element that displays a greeting using the user data.

  6. Export the App Component:

     export default App;
    

    Finally, we export the App component, which serves as the entry point for our application.

๐Ÿ“ค Output:

Conclusion ๐Ÿ’ฅ๐Ÿ™Œ

In conclusion, using prop drilling and using useContext Both give the same result but by using the useContext hook In React, we can efficiently pass data down to deeply nested child components without the need for prop drilling. This makes our code more readable, maintainable, and less repetitive. ๐Ÿš€


Thanks for reading all the way to the end! ๐Ÿ’–

If you have any questions, please use the comments section ๐Ÿ’ฌ

Let's connect! Find me on the web ๐Ÿ”—

If you have any Queries or Suggestions, feel free to reach out to me.

Happy Coding :)โค๏ธ

Did you find this article valuable?

Support Kushal Das by becoming a sponsor. Any amount is appreciated!

ย