Context in React
Tags: javascript, react, opensource, webdev
Published: 2021-10-26 18:09:25

What's this Context in ReactJS everyone's talking about! So according to the [React Documentation](https://reactjs.org/docs/context.html) _" Context provides a way to pass data through the component tree without having to pass props down manually at every level."_ 

So we can see it's a way to __pass data through the component tree without props at every level__. Well isn't it amazing! because it's like having global variables or in react terms something like global props. Let's take an example and go through the Context with React to get a good idea about it.

Very simple usage for such a feature might be using __Themes__ (Dark Theme/Light Theme) for your React Application (NOTE: __We must use Context for only the states which would not change regularly__). As themes are supposed to be passed to various components to change their appearance on say a click of a button anywhere in the component tree.


Now if we had usual props used to pass the data we might end up in trouble why? Let's say we have one application with a main component within it a brand component and a cards section inside it as shown below:
![React App Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1skbq86k16vybkezk5oi.png)

Now say you have a state maintained in Main Component and then use in cards section so you would have to pass it down all through from main to display and then get it in Cards component. This is a very basic structure and this approach is not very practical in web applications with complex structures.
<img width="100%" style="width:100%" src="https://media.giphy.com/media/XbmdBop1Fn6J3dT6U6/giphy.gif">
That's where the React Context comes to the rescue. Context provides a very simple structure for this purpose. Let's walk through the steps for using Context:

* You might have to create a context that we are gonna use for storing the global props and you might wanna do it in a separate component (For example here a theme Context is created).
```javascript
 const ThemeContext = React.createContext(); 
 ```

* Then you have to create a ContextProvider component which would wrap all the components of the app and it must contain all the states that are to be passed to each and every component which is wrapped in it.
```javascript
export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');
  const [backgroundColor, setBackgroundColor] = useState('bg-gray-100');
  const [textColor, setTextColor] = useState('black');
  const [cardsBackgroundColor, setCardsBackgroundColor] = useState('bg-white');
  const toggleTheme = () => {
    if (theme === 'light') {
      window.localStorage.setItem('theme', 'dark');
      setThemeColor('dark');
    } else {
      window.localStorage.setItem('theme', 'light');
      setThemeColor('light');
    }
  };
```
```javascript
 return (
    <ThemeContext.Provider
      value={{
        backgroundColor,
        textColor,
        cardsBackgroundColor,
        toggleTheme,
        theme,
      }}
    >
      {children}
    </ThemeContext.Provider>
  );
};
```
* So to use Context we actually need to wrap everything inside those Context and we do that generally by wrapping the whole App inside ReactDOM.render().
* Now that's all left is to use Context where we might wanna use it, but before we do that we would require to import Context wherever we want to use it. To keep all the things simple you might wanna expose a custom hook to keep the import of Context minimal.
```javascript
export const useContextTheme = () => {
  return useContext(ThemeContext);
};
```
* Finally Now we want to use our created Context, for that we would require the custom hook created by us in the previous step we import it and we are free to use it however we wish!

Import the context:
```javascript
import { useContextTheme } from 'components/ThemeContext';
```
Use inside your component:
```javascript
  const { toggleTheme, cardsBackgroundColor, theme } = useContextTheme();
```


Hurray! you are good to go for creating and using your own Contexts!
<img width="100%" style="width:100%" src="https://media.giphy.com/media/qYGvebgOKGygdQgflY/giphy.gif">