DEV Community

Cover image for useContext in React
Amogh Nandodkar
Amogh Nandodkar

Posted on

useContext in React

Understanding Context API

In order to understand useContext we need to first understand the context API. As we know, react uses state to store data and props to pass data from one component to another. This approach works well when there are only few components involved but gets more complex as the number of components increases. When deeply nested components are involved we end up using prop drilling in order to pass the props to the single component that is far down the hierarchy.

Context API simplifies this approach. Using context API we can specify certain data that needs to be available to all the components inside the context thus there is no need to pass the data through prop drilling or by any other approach. The data passed using the context API can be made available to all the components within that particular application. Here is an example:


const ResultContext = React.createContext();

export const ResultContextProvider = ({ children }) => {
  const [results, setResults] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('tesla');

  return (
    <ResultContext.Provider value={{ getResults, results, searchTerm, setSearchTerm, isLoading }}>
      {children}
    </ResultContext.Provider>
  );
};

Enter fullscreen mode Exit fullscreen mode

In the above example we created a new context using React.createContext(). This gives us a provider part and a consumer part.

The provider part provides values to all the components nested inside it. In the above example the value is a single object with getResults, results, searchTerm, setSearchTerm and isLoading in it.

The second part is the consumer. We need to wrap the code of the component in the consumer for it to be able to access the value of the context. Having to wrap the JSX in a component with the consumer adds extra layers of code. We can avoid all this mess in functional components by using the useContext hook.

useContext Hook

In order to start using the useContext we need to first import it as


import React, { createContext, useContext } from 'react';

Enter fullscreen mode Exit fullscreen mode

Further we can set up the context provider in a way similar to context API.


const ResultContext = createContext();

export const ResultContextProvider = ({ children }) => {
  const [results, setResults] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('tesla');

  return (
    <ResultContext.Provider value={{ getResults, results, searchTerm, setSearchTerm, isLoading }}>
      {children}
    </ResultContext.Provider>
  );
};

Enter fullscreen mode Exit fullscreen mode

With the help of useContext hook we can avoid the consumer part of the context API. We can do that in the following way:


import { useResultContext } from '../contexts/ResultContextProvider';

const Navbar = ({darkTheme, setDarkTheme}) => {
    const {results ,searchTerm} = useResultContext();

    return (
        <div className='flex flex-row text-center '>
              <div className='text-sm text-gray-400 text-center'>{results}</div>  
              <div className='text-sm text-gray-400 text-center'>{searchTerm}</div> 
        </div>
    )
}

export default Navbar


Enter fullscreen mode Exit fullscreen mode

In the above example we directly import useResultContext and it gives us all the context values which can be used as required.

Conclusion

The useContext hook simplifies the code as compared to the traditional context API which makes it fun to work with.

Top comments (0)