React Advanced

0% completed

Previous
Next
How to use ContextAPI and the useContext Hook

In this lesson, you'll learn about using the Context API and the useContext hook for global state management. You will explore step-by-step examples broken down to help you understand how it works better.

Let’s start by exploring a simple example of using the Context API to manage a theme (light or dark) across an application.

Example 1: Managing Global Theme with Context API

  1. Create the Context:

This is the first step is to create a context an give it a default value.

const ThemeContext = React.createContext('light');

Here, we've given the context a default value of 'light'.

  1. Wrap Components with Provider:

Using the Provide component, we want to accept a value prop, which is usually the data or state you want to make available to the rest of your application.

function App() { const [theme, setTheme] = useState('light'); return ( <ThemeContext.Provider value={theme}> <div> <h1>Current Theme: {theme}</h1> <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}> Toggle Theme </button> <ThemeDisplay /> </div> </ThemeContext.Provider> ); }

In this code example:

  • We declared a theme state and set it to a default of 'light'.
  • The Context Provider wraps the content making the theme value available to all child components.
  • <h1>Current Theme: {theme}</h1> renders the current theme dynamically.
  • Includes a button that conditionally toggles the theme between 'light' and 'dark' when clicked.
  • <ThemeDisplay /> is a separate component that can access the theme via ThemeContext.
  1. Consume Context with useContext:

We can now use the useContext hook to consume our created context:

function ThemeDisplay() { const theme = useContext(ThemeContext); return <div>The theme is currently: {theme}</div>; }

In this code, we accessed the ThemeContext data using the useContext hook by calling the 'theme' variable in any component we wish to use the theme toggling functionality.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next