Posts > Learning React Context API

Learning React Context API

  • Context API is a feature added in React 16.3 that allows to share states across the entire application.
  • It consists of two main components Context Provider and Context Consumer
πŸ‘ŒLess prop drilling ( passing props down manually at every level )
  • particularly useful for managing global data that needs to be shared between multiple components
  • It can be useful as well to store data retrieved from external sources such as API or databases and make it available to all components.

Context Provider

  • is a component wrapped in the component tree that is responsible for providing the data ( state ) to its child components
  • it accepts value props, which is the data you want to share
<MyContext.Provider value={` your data / state `} />
  {/* child components */}
</MyContext.Provider>
πŸ‘Œtypically you want to wrap your top-level component or a higher-level component with the context provider to make the data available to all its children components. Such as App.js

Context Consumer

  • A component that consumes the data provided by the Context Provider.
  • it uses the useContext hooks
  • will automatically re-render whenever the data it consumes changes to ensure it is up to date.
import { useContext } from 'react';

const myData = useContext(myContext);
πŸ‘Œwhere does the myContext comes from? what arguments does useContext needed?
Well the myContext is created using createContext in which we needed to pass into our useContext as a default data. The useContext accepts any kind of value ( even an object ).
import { createContext } from 'react';

export const myContext = createContext(/* any value ( even object )*/);

Use Cases for Context

  • Theming - change the appearance of your application from light to dark? put it into context so all its child components can update
  • Current Account - need to know the current logged-in user, and you need it for your components to use if the user has permission on the specific component
  • Routing - rerouting your user if it’s logged-in account has expired, or maybe you just want to redirect them to another part of your site.
  • Managing States - or you only want to pass some state to a lower component or maybe parent component?

Reference: https://react.dev/learn/passing-data-deeply-with-context#use-cases-for-context

How to use React Context API ( Theme toggling)

Let’s create a Theming Context that toggles our app theme from dark to light mode.

Step 1

  • create a context for the theme ThemeContext.js
import { useState, useContext, createContext } from 'react';

const ThemeContext = createContext();

export function useTheme(){
	return useContext(ThemeContext);
}

export function ThemeProvider({children}){
	const [ theme, setTheme ] = useState('light');

	const toggleTheme = () => {
		setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'))
	}

	return (
		<ThemeContext.Provider value={theme, toggleTheme}>
			{children}
		</ThemeContext.Provider>
	)
}
πŸ‘ŒWhat is happening in the code above?
ThemeContext - we created context
useTheme - custom hooks that access theme and toggleTheme function.
ThemeProvider - component that will wrap in our application that will provide the theme state and the toggleTheme function

Step 2

  • Wrap our Theme to your component
import { ThemeProvider } from './ThemeContext.js';

const App = () => {
	return (
		<ThemeProvider>
			<MainContent />
		</ThemeProvider>
	)
}

Step 3

  • Use the Theme in our MainContent component
import { useTheme } from './ThemeContext';

const MainContent = () => {
	const { theme, toggleTheme }	= useTheme();
	return(
		<div className={`${theme}`}> /* lets imagine we have styling class for light and dark mode available :P */ 
			<button onClick={toggleTheme}>Toggle Theme</button>
		</div>
	)
}
πŸ‘ŒCode Sample: https://codesandbox.io/s/react-context-api-5pjh9p

Tags 🏷