Introduction:
React is a widely used JavaScript library for building single-page applications. When managing state, small projects often use local state within components, while large and complex projects use React Redux to manage state across multiple files. However, React Context API offers a way to manage global state without Redux.
This blog will show you how to use the React Context API for global state management without Redux. We will cover practical examples and highlight when the Context API is most effective.
React Context API:
With the use of this, you can send the data from one component to another. It helps manage the data and functionality of different levels of components with the use of props. It is used to avoid the prop drilling problem.
Syntax:
import { createContext } from 'react';
const MyData = createContext(defaultValue);
Example
Code:
export const ThemeProvider = ({ child }) => {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
setTheme(theme === "light" ? "dark" : "light");
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{child}
</ThemeContext.Provider>
);
};
Core features of Context API
The React context API contains three core elements.
1) React.createContext(): Firstly, it will help to make a new context. Also, it provides a context object with the two components, such as the provider and consumer.
2) Context.Provider: It helps to manage the application and return a value for the child components. With the use of a provider in the component, it is easy to access the data.
3) Context.Consumer: This component receives context data and can be easily re-rendered.
How Context API works?
Context API works in three phases, as mentioned below.
Step 1) Create the Context:
Example
Code:
import React, { createContext, useState } from 'react';
// Step 1: Create the context
export const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(prev => (prev === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
Step 2) Use the provider:
Example
Code:
// App.js
import React from 'react';
import { ThemeProvider } from './ThemeContext';
import ThemeSwitcher from './ThemeSwitcher';
const App = () => {
return (
<ThemeProvider>
<div>
<h1>React Context API Example</h1>
<ThemeSwitcher />
</div>
</ThemeProvider>
);
};
export default App;
Step 3) Use the Context in Component:
Example
Code:
// ThemeSwitcher.js
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
const ThemeSwitcher = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
const styles = {
backgroundColor: theme === 'light' ? '#f0f0f0' : '#333',
color: theme === 'light' ? '#000' : '#fff',
padding: '20px',
textAlign: 'center',
};
return (
<div style={styles}>
<p>Current theme: {theme}</p>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};
export default ThemeSwitcher;
When you use the Context API:
• If the developers want to manage the global data with multiple components, such as user authentication(signup/login), theme changes, etc.
• With the use of this, you can easily avoid the prop drilling problem.
• You cannot make data changes in one or more times. If you change, an occurrence of a performance issue.
• It helps to maintain the code, make it reusable, flexible, or easier to read.
Practical Examples of Context API
Theme Setting App (light/Dark Mode):
With the use of this app, you can easily change the screen mode, such as light and dark modes.
Step 1) Make the Theme Context:
// context/ThemeContext.js
import { createContext } from 'react';
const ThemeContext = createContext();
export default ThemeContext;
Step 2) Make the theme provider:
// components/ThemeProvider.js
import React, { useState, useMemo } from 'react';
import ThemeContext from '../context/ThemeContext';
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => setTheme(prev => prev === 'light' ? 'dark' : 'light');
const value = useMemo(() => ({ theme, toggleTheme }), [theme]);
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
);
};
export default ThemeProvider;
Step 3) Make a theme changer component:
// components/ThemeSwitcher.js
import React, { useContext } from 'react';
import ThemeContext from '../context/ThemeContext';
const ThemeSwitcher = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<button onClick={toggleTheme}>
Switch to {theme === 'light' ? 'Dark' : 'Light'} Mode
</button>
);
};
export default ThemeSwitcher;
Step 4) Make page component:
// components/Page.js
import React, { useContext } from 'react';
import ThemeContext from '../context/ThemeContext';
const Page = () => {
const { theme } = useContext(ThemeContext);
const style = {
background: theme === 'dark' ? '#222' : '#fff',
color: theme === 'dark' ? '#fff' : '#000',
padding: '2rem',
minHeight: '100vh',
};
return <div style={style}>This is a {theme} themed page.</div>;
};
export default Page;
Step5) Main file(index.js):
// index.js
import React from 'react';
import ThemeProvider from './components/ThemeProvider';
import ThemeSwitcher from './components/ThemeSwitcher';
import Page from './components/Page';
const App = () => (
<ThemeProvider>
<ThemeSwitcher />
<Page />
</ThemeProvider>
);
export default index;
Limitations of Context API
React context API uses the props drilling concept, but this concept is used for sending the data from parent to child component one by one.
1) High complexity:
Components are used for sending data through the props and also receiving data. Only one issue using these components will be re-rendering.
2) Only used for small tool support:
React state uses a high-level tool for debugging the component, but the Context API supports only a small built-in support.
3) Performance issue:
This can be provided using the Context.Provider method. This issue occurs when you are working in large applications that require frequent changes to the context value.
Conclusion
This article gives you a deep understanding of React Context API, managing the State without Redux, from basic to advanced levels of developers. It provides a better solution for managing the state, with less complex code. Also, it supports the features of sending data from one component to another component using the props drilling. React Redux is used for handling large and complex applications.
For a detailed and clear understanding of ReactJS, Tpoint Tech provides React tutorials, all related concepts, and interview questions.
