Context in React

What’s this Context in ReactJS everyone’s talking about! So according to the React Documentation ” 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 …


This content originally appeared on DEV Community and was authored by Sahil

What's this Context in ReactJS everyone's talking about! So according to the React Documentation " 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. 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

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.

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).
 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.
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');
    }
  };
 return (
    <ThemeContext.Provider
      value={{
        backgroundColor,
        textColor,
        cardsBackgroundColor,
        toggleTheme,
        theme,
      }}
    >
      {children}
    </ThemeContext.Provider>
  );
};
  • 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.
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:

import { useContextTheme } from 'components/ThemeContext';

Use inside your component:

  const { toggleTheme, cardsBackgroundColor, theme } = useContextTheme();

Hurray! you are good to go for creating and using your own Contexts!


This content originally appeared on DEV Community and was authored by Sahil


Print Share Comment Cite Upload Translate Updates
APA

Sahil | Sciencx (2021-10-26T18:09:25+00:00) Context in React. Retrieved from https://www.scien.cx/2021/10/26/context-in-react/

MLA
" » Context in React." Sahil | Sciencx - Tuesday October 26, 2021, https://www.scien.cx/2021/10/26/context-in-react/
HARVARD
Sahil | Sciencx Tuesday October 26, 2021 » Context in React., viewed ,<https://www.scien.cx/2021/10/26/context-in-react/>
VANCOUVER
Sahil | Sciencx - » Context in React. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/26/context-in-react/
CHICAGO
" » Context in React." Sahil | Sciencx - Accessed . https://www.scien.cx/2021/10/26/context-in-react/
IEEE
" » Context in React." Sahil | Sciencx [Online]. Available: https://www.scien.cx/2021/10/26/context-in-react/. [Accessed: ]
rf:citation
» Context in React | Sahil | Sciencx | https://www.scien.cx/2021/10/26/context-in-react/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.