DEV Community

AYON KARMAKAR
AYON KARMAKAR

Posted on

1 1 1 1 1

React Context – Quick Revision Notes

🔹 Definition: Context API manages global state and avoids prop drilling.


1️⃣ Create Context

const MyContext = createContext(defaultValue);
Enter fullscreen mode Exit fullscreen mode

2️⃣ Provide Context

<MyContext.Provider value={sharedData}>
  <App />
</MyContext.Provider>
Enter fullscreen mode Exit fullscreen mode

3️⃣ Consume Context

  • ✅ With useContext (Functional Components)
const value = useContext(MyContext);
Enter fullscreen mode Exit fullscreen mode
  • ✅ With Context.Consumer (For Class Components)
<MyContext.Consumer>
  {value => <div>{value}</div>}
</MyContext.Consumer>
Enter fullscreen mode Exit fullscreen mode

🚀 Example (Sidebar Context)

"use client";

import { useIsMobile } from "@/hooks/use-mobile";
import { createContext, useContext, useEffect, useState } from "react";

type SidebarState = "expanded" | "collapsed";

type SidebarContextType = {
  state: SidebarState;
  isOpen: boolean;
  setIsOpen: (open: boolean) => void;
  isMobile: boolean;
  toggleSidebar: () => void;
};

const SidebarContext = createContext<SidebarContextType | null>(null);

export function useSidebarContext() {
  const context = useContext(SidebarContext);
  if (!context) {
    throw new Error("useSidebarContext must be used within a SidebarProvider");
  }
  return context;
}

export function SidebarProvider({
  children,
  defaultOpen = true,
}: {
  children: React.ReactNode;
  defaultOpen?: boolean;
}) {
  const [isOpen, setIsOpen] = useState(defaultOpen);
  const isMobile = useIsMobile();

  useEffect(() => {
    if (isMobile) {
      setIsOpen(false);
    } else {
      setIsOpen(true);
    }
  }, [isMobile]);

  function toggleSidebar() {
    setIsOpen((prev) => !prev);
  }

  return (
    <SidebarContext.Provider
      value={{
        state: isOpen ? "expanded" : "collapsed",
        isOpen,
        setIsOpen,
        isMobile,
        toggleSidebar,
      }}
    >
      {children}
    </SidebarContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

⚡ Best Practices

  • ✅ Use multiple contexts for modularity.
  • ✅ Combine with useReducer for complex state.
  • ✅ Wrap context logic in a custom hook for cleaner code.
const useMyContext = () => useContext(MyContext);
Enter fullscreen mode Exit fullscreen mode

🚀 Use Context for: Theme, Auth, Language, Global State.

Build the product, not the plumbing—React first

Build the product, not the plumbing—React first

Kinde handles the boring but critical stuff: auth, permissions, and billing—all from one React SDK.

Get a free account

Top comments (0)

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server 🏁

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post

👋 Kindness is contagious

Take a moment to explore this thoughtful article, beloved by the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A heartfelt "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay