Context Hook
Tags: javascript, react, webdev, programming
Published: 2022-01-16 07:22:06

> It helps in providing data to components.
Generally in react what happens that whenever we our working on a small project the data is passed from parent to child , where we have one or two component we can easily make use of props to pass the data.

But when it comes to big project when there are no of components and we have to pass the data which will be used by almost every component or we don’t have to pass data in hierarchy then passing data through the props become little bit unmanageable so in order to prevent this context provides a way to pass the data to different components
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/71ncsoonurgdcz3evequ.png)
 
context is majorly used when the data is global let me take you through an example suppose you are calling an Api  and different components are accessing different data of the Api then you just can’t manually pass the data through props you need a proper system to manage your data flow so that it can be easily accessed by every component.

### When To use Context?

the image shown below is enough to tell you when to make use of it
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/avcl968omros3za6llza.png)
let me dive you through a project with which your understanding towards it will get better and will also be introducing you to the `createcontext` and `context.provider `

```
import React, { createContext, useContext, useEffect, useState } from 'react'
// import { useNavigate } from 'react-router-dom';


const Food=createContext();

const key="d90a7bf3";
const API="b1d3f3b888a6b98ec1aa24c610480f2f";
const FoodContext = ({children}) => {

    const [recipes, setrecipe] = useState([]);
    const [search, setsearch] = useState("");
    const [query, setquery] = useState('');
// const navigate=useNavigate();
 
    useEffect(()=>{
        getrecipes();
      },[query]);
      
      const updatesearch=e=>{
        setsearch(e.target.value);
     
      }
      const getrecipes=async()=>{
      const response =await fetch(`https://api.edamam.com/search?q=${query}&app_id=${key}&app_key=${API}`);
      const data=await response.json();
      setrecipe(data.hits);
      }

    return (
        <Food.Provider value={{setquery,recipes,search,setsearch,updatesearch}}>
            {children}
        </Food.Provider>
    )
}

export default FoodContext

export const FoodState=()=>{
    return useContext(Food);
}
```
This is our foodcontext.js  

`const Food=createContext();` talking about this here we are doing nothing just calling api `createContext` from react.

Moving further as you can see we are making an api call and accessing the data from the api which is to be accessed by different components.

Here comes the `Food.Provider` basically in context with the help of it we pass the data to the descendants . It takes value as an prop where we refer to the data which we have to actually pass to the components.

Now comes the `useContext` so up till now we have done everything we have call the api  and passed the data but the most important thing left that we also have to use that data here `useContext` plays a significant role it helps in using the data which is passed through the context. 

Once we are done with all this we have to put our app.js inside the `FoodContext`.
 

```
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import FoodContext from './FoodContext';
// import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <FoodContext>
    <App />
    </FoodContext>
  </React.StrictMode>,
  document.getElementById('root')
```
When we are done with all this we are finally left with using the data in a particular component

```
import React from 'react'
import { useNavigate } from 'react-router-dom';
// import { Link } from 'react-router-dom';
import { FoodState } from '../FoodContext'
// import * as React from 'react';

const Header = () => {
    const navigate=useNavigate();

    const {setquery,setsearch,search,updatesearch}=FoodState();

    const getsearch=(e)=>{
        e.preventDefault();
        setquery(search);
       navigate("/food");
        setsearch('');
      }

    return (
        <div className="navbar">
<div className="text">
    Nagpal's 
</div>
<div className="search">

        <form  onSubmit={getsearch}  className="searchfrom">
        <input className="searchbar" type={search} onChange={updatesearch} />
        <button   className="searchbutton">Search</button>
       
      </form>
</div>
        </div>
     
    )
}

```
So as you can see here we are accessing the data from the context  by `destructuring` the data from `FoodState()`.