DEV Community

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

Posted on

4

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!

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil β€” patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

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 .......😍

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup πŸš€

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay