Learn the useContext Hook in React

ยท

3 min read

Learn the useContext Hook in React

What is React Context


Imagine for a moment that you have a react app with a single parent component that contains many levels of child components inside of it.

Now, imagine passing data from the uppermost component all the way down to the last child component.

In React data is passed top-down from one component to another component through props.

You'd have to pass that data through each and every component, through their props, until you reach the last child component.

Suppose, you'd have to only pass one parameter parent component to the last child component using props is not a good approach. In that case where Context comes useful in the react.

The React Context API allows you to easily access data at different levels of the component tree, without having to pass data down through props.

Here's an example

Let's say have an App component. Inside that App component, you have a User component. Inside the User component, you have a Greeting component.

So code structure layout:

     App Component --> User Component --> Greeting Component

Now, let's say you have a user in your App(parent) component, and you want to pass the user property into the Greeting (nested child) component.

Normally, you'd have to send that property through the User component, then into the Greeting component. Like so:

    // App.js
    const App = () => {
        let userName = "Alice";
        return <User userName={userName}/>
    }
    // User.js
    const User = (props) => {
         return <Greeting userName={props.userName} />
    }
    // Greeting.js
    const Greeting = (props) => {
         return `Happy BirthDay, {props.userName} :)`
   }

Create a Context

To start using useContext, you must first create a context. You'd have created a separate file for DataContext, in that import createContext and useContext from React.

     // DataContext.js
     import {createContext,useContext} form 'react';

     const DataContext = createContext('');
     // create Data Provider
     const DataProvider = ({children}) => {
          const userName = "Alice";
          return(
             <DataContext.Provider value={{userName}}>
                     {children}
             </DataContext.Provider>
      }
     // create useContext
     const useData = () => useContext(DataContext)

     export {DataProvider,useData}

All we need to do to access the Context's state is import useData into the component.

Jump over to index.js and import the DataProvider component. Then, wrap it around an App component.

     // index.js
     import ReactDOM from 'react-dom';
     import App from './App';
     import {DataProvider} from './DataContext';

     ReactDOM.render(
         <React.StrictMode>
                <DataProvider>
                    <App/>
                </DataProvider>
         </React.StrictMode>,
         document.getElementById('root')
     );

    // app.js
    import React from 'react';
    import User from './User';
    import Greeting from './Greeting';

    const App = () => {
     return(
         <>
           <User/>
           <Greeting/>
         </>
    );
   export default App;

Note that now, we're not sending the userName into User. We're sending it into DataContext Provider via value={{userName}}. We can grab that value in any of the nested components.

Consume the context

To consume the value in any nested component, we have to import useData custom hook.

     // Greeting.js
     import React from 'react';
     import {useData} from './DataContext';

     const Greeting = () => {
         const {userName} = useData();
         return (
             <>
                <h3>Happy BirthDay, {userName} :)</h3>
             </>
        );
     };
     export default Greeting;

The DataContext will return the value that we sent into DataContext.Provider value={{userName}}. We're saving it in the Greeting component to a const variable userName.

Now, we're free to use that constant/value in our Greeting component, and we never had to touch the User component.

Conclusion

The useContext hook is a very useful tool in React. It could be used for changing a theme and updating that theme in the different components it needs to. It prevents prop drilling.

Thanks for read this article ๐Ÿ˜† ๐Ÿ˜† ๐Ÿ‘

ย