In this tutorial, you will learn how to manage global state in React using the Context API and how to leverage hooks for cleaner and reusable logic.
Introduction
In small React apps, passing props through multiple components is fine. But in larger apps, managing global state can become messy. The Context API helps share state across components without prop drilling. Hooks allow you to reuse logic in functional components efficiently.
1. What Is the Context API?
The Context API allows you to create a global state accessible by any component within a provider.
Example: Creating a theme context:
import { createContext } from 'react';
export const ThemeContext = createContext('light');
2. Using the Provider
Wrap your component tree with the context provider:
import { ThemeContext } from './ThemeContext';
function App() {
const theme = 'dark';
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
</ThemeContext.Provider>
);
}
3. Consuming Context
Access the context value in child components using the useContext hook:
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Toolbar() {
const theme = useContext(ThemeContext);
return <div>Current theme: {theme}</div>;
}
4. Using Other Hooks
- useState: Manage local state in functional components.
- useEffect: Run side effects such as API calls.
- useReducer: Manage complex state logic.
Hooks simplify component logic and improve code readability.
5. Example: Theme Switcher
import { useState, useContext, createContext } from 'react';
const ThemeContext = createContext();
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{theme, setTheme}}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Toggle Theme</button>
</div>
);
}
export default App;
6. Summary
In this tutorial, you learned:
- How to create and use the Context API to share state globally
- How to consume context using
useContext - Common React hooks:
useState,useEffect,useReducer - How to build a small theme switcher app using context and hooks
Next, in React Beginner 9, you will learn how to connect your React frontend with a Spring Boot backend for a full-stack project.