Introduction
React Hooks have revolutionized how developers manage state and side effects in functional components.
One such powerful hook is useContext
, which simplifies state management by providing a way to share values across components without the need for prop drilling.
In this article, weβll explore how to use useContext
effectively in a TypeScript-based React project.
What is useContext? π€
The useContext
hook allows functional components to access values from a React context.
It is commonly used to share global state, themes, authentication status, and more, without passing props manually down the component tree.
Setting Up Context in TypeScript
To effectively use useContext
with TypeScript, itβs essential to define the context's value type. Letβs go through an example step by step.
Step 1: Create a Context
First, define a context with a proper TypeScript type.
import { createContext } from "react";
type ThemeContextType = {
theme: "light" | "dark";
toggleTheme: () => void;
};
export const ThemeContext = createContext<ThemeContextType | null>(null);
Step 2: Create a Provider Component
A provider component supplies the context to its children. Hereβs how we define it:
import { ReactNode, useState } from "react";
import { ThemeContext } from "./ThemeContext";
type ThemeProviderProps = {
children: ReactNode;
};
export const ThemeProvider = ({ children }: ThemeProviderProps) => {
const [theme, setTheme] = useState<"light" | "dark">("light");
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
Step 3: Using useContext in a Component
Now, letβs consume this context in a functional component using useContext
.
import { useContext } from "react";
import { ThemeContext } from "./ThemeContext";
export const ThemeSwitcher = () => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("ThemeSwitcher must be used within a ThemeProvider");
}
const { theme, toggleTheme } = context;
return (
<div>
<p>Current Theme: {theme}</p>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};
Step 4: Wrap Components with Provider
Finally, wrap the main application component with ThemeProvider
to ensure context availability.
import React from "react";
import ReactDOM from "react-dom/client";
import { ThemeProvider } from "./ThemeProvider";
import { ThemeSwitcher } from "./ThemeSwitcher";
const App = () => (
<ThemeProvider>
<ThemeSwitcher />
</ThemeProvider>
);
const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
root.render(<App />);
Benefits of Using useContext β
1- Avoids Prop Drilling: Eliminates the need to pass props through multiple component levels.
2- Improves Code Maintainability: Centralized state management makes it easier to manage changes.
3- Enhances Readability: Cleaner and more concise code structure.
4- Encourages Reusability: Context values can be shared across multiple components.
Best Practices π―
Use Context Wisely: Avoid using
useContext
for frequently changing values, as it may trigger unnecessary re-renders.Combine with Reducers: For complex state logic, combine
useContext
withuseReducer
.Always Provide a Default Value: Ensure a valid default context value to prevent runtime errors.
Modularize Context Providers: Create separate providers for different concerns like themes, authentication, and settings.
Conclusion β‘
The useContext
hook is a game-changer for state management in React applications. When combined with TypeScript, it ensures type safety and enhances the overall development experience.
By following best practices and structuring your context properly, you can build scalable and maintainable React applications with ease.
π Connect With Me On:
π LinkedIn
π X (Twitter)
π Telegram
π Instagram
Happy Coding!
Top comments (2)
there is ready made library for collection of modern, server-safe React hooks usehooks.com
very Helpful .......π