Skip to main content

Context API in React (Live Playground)

The Context API is a powerful feature in React that enables you to share state across multiple components without having to pass props through the component tree. In this tutorial, we'll dive into the Context API, providing sample code and simple explanations to help you get started.

Creating a Context

First, let's create a context using React.createContext. This will create a new context with a default value:

JavaScript
import React from 'react';

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

export default ThemeContext;

In this example, we've created a ThemeContext with a default value of light.

Providing Context Value

To provide the context value to child components, we can use the Provider component exported by the context:

JavaScript
import React from 'react';
import ThemeContext from './ThemeContext';
import ThemedButton from './ThemedButton';

function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedButton />
</ThemeContext.Provider>
);
}

export default App;

In this example, we've wrapped the ThemedButton component with the ThemeContext.Provider component and provided a value of dark.

Consuming Context Value

To consume the context value within a component, we can use the useContext hook:

JavaScript
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';

function ThemedButton() {
const theme = useContext(ThemeContext);
console.log('Current theme:', theme);

return <button className={`btn btn-${theme}`}>Themed Button ({theme})</button>;
}

export default ThemedButton;

In this example, we've used the useContext hook to access the current value of ThemeContext and applied it as a class name to the button.

Updating Context Value

To update the context value, you can use local state in a parent component and pass the state and state update function as context values:

JavaScript
import React, { useState } from 'react';
import ThemeContext from './ThemeContext';
import ThemedButton from './ThemedButton';

function App() {
const [theme, setTheme] = useState('light');

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

return (
<ThemeContext.Provider value={theme}>
<ThemedButton />
<button onClick={toggleTheme}>Toggle Theme</button>
</ThemeContext.Provider>
);
}

export default App;

In this example, we've added a toggleTheme function to change the theme between light and dark and provided the updated value to the ThemeContext.Provider.

Live Playground, Try it Yourself
JavaScript / TypeScript
const useState = React.useState;
const useContext = React.useContext;

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

function ThemedButton() {
const theme = useContext(ThemeContext);
console.log('Current theme:', theme);

return <button className={`btn btn-${theme}`}>Themed Button ({theme})</button>;
}

function App() {
const [theme, setTheme] = useState('light');

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

return (
<ThemeContext.Provider value={theme}>
<ThemedButton />
<button onClick={toggleTheme}>Toggle Theme</button>
</ThemeContext.Provider>
);
}


const domContainer = document.querySelector('#root');
const root = ReactDOM.createRoot(domContainer);
root.render(<App/>);
Preview
Console

Conclusion

In this tutorial, we've explored the Context API in React, learning how to create, provide, consume, and update context values. The Context API is a powerful tool for state management that simplifies the sharing of state across multiple components.

Make use of the Context API in your projects to efficiently manage and share state, resulting in cleaner and more maintainable code.