Introduction:
Renowned for its efficiency and flexibility, the React framework provides numerous features that enable developers to build robust and scalable web applications. One standout feature is the React Context API, which allows developers to manage state and share data across the component tree without relying on prop drilling. The Context API is particularly valuable for handling “global” data needed by multiple components, such as user authentication and theme settings.
Prerequisites:
- Node.js and npm
- React
- Typescript
- React Hooks
Understanding Advance Usage of Context API:
The following sections will offer a deeper dive into the Context API. Whether you’re new to React or looking to enhance your knowledge of state management, this blog will give useful insights and guidance.
- Understanding the Basics of React Context:
Introduced in React 16.3, React Context is a feature that enables data sharing between components without the need to pass it through props. The Context API addresses the issue of “prop drilling,” where data must be passed down from top-level components to lower levels in the component tree. By using the Context API, you can share data globally across the entire component tree, simplifying the process.
- When & When not to use the Context API:
It is useful when data needs to be shared across multiple components that are not directly related to each other.
React Context has its drawbacks, and overusing it can lead to performance problems. When the context value updates, it can trigger unnecessary re-renders in consuming components, even if the updates are irrelevant to them. This can negatively affect performance, especially in larger component trees.
For frequently updated states, React Context might not be as efficient as tools like React Redux. However, for static data that updates infrequently, such as preferred language, time changes, location changes, and user authentication, React Context is a suitable choice for passing down props.
- Context API vs Redux:
Choosing between React Context API and Redux depends on the specific requirements and complexity of your application.
Use React Context API:
- Small to medium-sized applications
- Fewer levels of data sharing
- Component-specific state
Use Redux:
- Large and complex applications
- Deeply nested components
- Asynchronous data flow
- Use Cases of Context API:
Following are some real-world use cases of Context API
- Multi-Language Support: You can store the current language of your application in the context and pass it down to all the components that require it. This way, you can easily switch between different languages without having to pass the language down as props to all the components.
- User Authentication: You can use Context API to store a user’s authentication status and pass it down to all the components that require it. This way, you can easily restrict access to certain parts of your application based on the user’s authentication status.
- Theming: Utilizing the Context API enables you to store the current theme of your application and share it with all components. Consequently, whenever the user changes the theme, all components will automatically reflect the new theme.
- Accessing data from external sources: The Context API can be used to store data fetched from external sources, such as APIs or databases, and make it accessible to all components. This approach can simplify your code and streamline data handling across your application.
A Comprehensive Guide to Application:
This React + TypeScript application is a simple counter app demonstrating the use of the Context API for state management. By using the Context API, the state is efficiently shared and managed across components without the need for prop drilling. This setup showcases a clean and scalable approach to handling the global state in a React application.
By following the below steps, you can easily learn how to use context API and also make an application where you leverage the advantages of context API.
- There is a folder for components, where all the necessary components for the application will be created.
- There is a folder named assets, where all the styling files will be stored.
- Then, a separate folder is created for the context.
Navigating the Frontend Setup In React:
Let’s start the UI implementation for using React with a TypeScript template.- Initializing React Application: To create a React application, you need to start by creating a project folder in your root directory. Inside the project folder, install the necessary dependencies by running the following commands.
npx create-react-app context-api –template typescript |
- Please follow the below steps to make the theming app using context API for state management. In the project context-api folder, locate the App.tsx file which serves as the entry point for the project.
-
- Create a separate folder for the components where you will create the necessary components.
- In that components folder, make a file named Container.tsx and Card.tsx.
- Make a separate folder named context. In that folder make a file with the name DarkModeContext.tsx.
- Design the user interface according to your preference using raw CSS or any library of your choice.
//App.tsx
import Container from "./components/Container/Container";
import { DarkModeProvider } from "./context/DarkModeContext";
import './App.css'
function App() {
return (
);
}
export default App;
- In the App component, the Container component is wrapped inside the DarkModeProvider, so all the child components will be able to use the context value.
//DarkModeContext.tsx
import React, {
Dispatch,
SetStateAction,
createContext,
useState,
} from "react";
interface DarkModeContextType {
darkMode: boolean;
toggleDarkMode: Dispatch>;
}
const DarkModeContext = createContext({
darkMode: false,
toggleDarkMode: () => {},
});
function DarkModeProvider(props: any) {
const [darkMode, setDarkMode] = useState(false);
const toggleDarkMode = () => {
setDarkMode(!darkMode);
};
return (
{" "}
{props.children}
);
}
export { DarkModeContext, DarkModeProvider };
- This code defines a DarkModeContext using the createContext() method from the React and the Provider component. The Provider component is then used in the App component, which wraps a child component called Container.
//Container.tsx
import { useContext } from "react";
import { DarkModeContext } from "../../context/DarkModeContext";
import Card from "../Card/Card";
import "./Container.css";
import DarkMode from "../../assets/images/sun-svgrepo-com.svg";
import LightMode from "../../assets/images/sun-summer-svgrepo-com.svg";
const Container = () => {
const { darkMode, toggleDarkMode } = useContext(DarkModeContext);
return (
toggleDarkMode(darkMode)}
src={darkMode ? LightMode : DarkMode}
alt="sun_svg"
/>
);
};
export default Container;
- The Container component uses the useContext() hook to access the darkMode and toggleDarkMode values from the DarkModeContext. It then displays the clickable image to toggle between the dark and light mode.
- To toggle the mode value in the DarkModeContext, you can use the toggleDarkMode() function provided by the context.
- The toggleDarkMode() function is used to update the dark mode value when the image is clicked.
//Card.tsx
import { useContext } from "react";
import { DarkModeContext } from "../../context/DarkModeContext";
const Card = () => {
const { darkMode } = useContext(DarkModeContext);
return (
{darkMode
? "Please turn on the light. It's too dark here..."
: "It's too bright here. I can't open my eyes..."}
);
};
export default Card;
- Here, in the Card component, we are using dardMode value from the DarkModeContext and then applying styling to the elements depending on the value of the darkMode.
Conclusion:
In conclusion, the Context API is a powerful feature of React that allows sharing of data among components without the need to pass props manually down through the component tree. Centralizing state management with the Context API can simplify code, enhance performance, and reduce the need for prop drilling, leading to more accessible applications. The creation of context objects using createContext() method and then the use of Provider and Consumer components to share data among components were discussed. Finally, we looked at an example of how to use the Context API in a simple application and how to update the Context. Overall, Context API is a valuable tool that React developers should have in their toolkit.