DEV Community

Cover image for Simplifying React Hooks: useContext πŸ’―
Ali Samir
Ali Samir

Posted on

Simplifying React Hooks: useContext πŸ’―

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);
Enter fullscreen mode Exit fullscreen mode

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>
  );
};
Enter fullscreen mode Exit fullscreen mode

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>
  );
};
Enter fullscreen mode Exit fullscreen mode

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 />);
Enter fullscreen mode Exit fullscreen mode

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 with useReducer.

  • 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)

Collapse
 
shahidkhans profile image
Shahid

there is ready made library for collection of modern, server-safe React hooks usehooks.com

Collapse
 
ravi-coding profile image
Ravindra Kumar

very Helpful .......😍