Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Hooks

React Context and Custom Hooks: Share One Value, Reuse the Logic

Replace three hops of prop drilling with a context, see the nearest Provider win, count which components re-render on a theme toggle, then pull localStorage logic into a useLocalStorage hook and break the rules of hooks on purpose.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Hooks

What you will learn

  • Recognise prop drilling and replace it with createContext, a Provider and useContext
  • Predict which Provider a component reads, and what it gets with none
  • Keep shared state in a Provider and know which components re-render when it changes
  • Extract logic into a custom hook, and follow the rules of hooks

Before you start

  • React props, state and useEffect
  • Lifting state up

Some values are needed all over a page: the signed-in user, the theme. Passing them as props through every level gets painful fast. Context shares one value with a whole region of the tree. A custom hook does something different: it shares logic between components, not state. This article traces both with the lecture's task app.

Prop drilling: hop by hop

// The painful way: props passed down every level.
type Props = { user: string; theme: string }

export function DrillApp() {
  return <Page user="Emma" theme="dark" />
}

// Page does not use user or theme: it passes them on
function Page({ user, theme }: Props) {
  return <Sidebar user={user} theme={theme} />
}

// and neither does Sidebar
function Sidebar({ user, theme }: Props) {
  return <UserBadge user={user} theme={theme} />
}

// the only component that really uses them
function UserBadge({ user, theme }: Props) {
  return <p className={theme}>Signed in as {user}</p>
}
page: Signed in as Emma
class: dark

Three hops, and two components (Page and Sidebar) that never use the values and only pass them on. Add one more prop and you edit every level on the way down. That is prop drilling.

createContext and the Provider

import { createContext, type ReactNode } from 'react'
import { countRender } from './renders'

export type User = { name: string; role: string }
type Props = { children: ReactNode }

// null is the default: what useContext gives
// when there is no Provider above
export const UserContext =
  createContext<User | null>(null)

export function UserProvider({ children }: Props) {
  countRender('UserProvider')
  const user: User = { name: 'Emma', role: 'Admin' }
  // everything inside children can read user
  return (
    <UserContext value={user}>
      {children}
    </UserContext>
  )
}

createContext(null) makes the context, and null is its default, used only when there is no Provider above. Lines 17 to 19 render the context itself as a Provider with a value (in React 19 you write <UserContext value={user}> directly). Every component inside children, at any depth, can read that value.

useContext looks up the tree

import { useContext } from 'react'
import { UserContext } from './UserContext'
import { countRender } from './renders'

export function UserBadge() {
  countRender('UserBadge')
  // asks the nearest UserContext Provider above
  const user = useContext(UserContext)
  const name = user ? user.name : 'nobody'
  return <p className="badge">Signed in as {name}</p>
}
useContext finds the nearest Provider UserContext value = Emma Layout (no props) Sidebar (no props) UserBadge useContext(UserContext) asks up the tree, stops at the nearest Provider
Layout and Sidebar pass nothing. They don't even know about the user.

The nearest Provider, or the default

A small script renders UserBadge with no Provider, with one, and with a second Provider for Jack nested inside the Emma one:

no Provider:     Signed in as nobody
one Provider:    Signed in as Emma
nested Provider: Signed in as Jack

useContext stops at the first Provider it meets going up. With no Provider at all, it gets the default from createContext.

The state lives in the Provider

import { createContext, useState } from 'react'
import type { ReactNode } from 'react'
import { countRender } from './renders'

export type Theme = 'light' | 'dark'
type ThemeValue = { theme: Theme; toggle: () => void }
type Props = { children: ReactNode }

// the default: used when no Provider is above
export const ThemeContext = createContext<ThemeValue>({
  theme: 'light',
  toggle: () => {},
})

export function ThemeProvider({ children }: Props) {
  countRender('ThemeProvider')
  // the state lives here, in ONE place
  const [theme, setTheme] = useState<Theme>('light')
  const toggle = () =>
    setTheme(theme === 'light' ? 'dark' : 'light')
  return (
    <ThemeContext value={{ theme, toggle }}>
      <div className={'app ' + theme}>{children}</div>
    </ThemeContext>
  )
}

The theme is a normal useState, kept in one place, inside the Provider. The Provider's value is an object with theme and toggle, built fresh on every render. ThemeToggle reads both with no props at all:

import { useContext } from 'react'
import { ThemeContext } from './ThemeContext'
import { countRender } from './renders'

export function ThemeToggle() {
  countRender('ThemeToggle')
  // no props: theme and toggle come from the Provider
  const { theme, toggle } = useContext(ThemeContext)
  return (
    <button onClick={toggle}>
      {theme === 'light' ? 'Dark mode' : 'Light mode'}
    </button>
  )
}
The task app twice. Left, light theme: Signed in as Emma, a Dark mode button, and Team tasks with Write report, Email Jack and Book flights. Right, after the click, dark theme with a Light mode button.
Before and after one click on Dark mode. The badge and the button read two different contexts.

Who re-renders when the value changes?

Each component counts its renders. Click Dark mode once:

first render: 7 components, 1 render each
click: Dark mode
ThemeProvider: 2 renders
ThemeToggle: 2 renders
still 1: UserProvider, Layout, Sidebar, UserBadge, Tasks
page: button "Light mode", class "app dark"

The toggle sets the state in ThemeProvider, so it renders again and gives a new value. React re-renders every component that reads that context, here ThemeToggle. The other five stay at one render: they were created by App, outside the Provider, so React can skip them.

Remember the theme: from inline code to a custom hook

Now we want the theme to survive a reload. Written by hand inside the Provider:

export function ThemeInline({ children }: Props) {
  // first render: read the saved theme, or 'light'
  const [theme, setTheme] = useState<Theme>(() => {
    const saved = localStorage.getItem(key)
    return saved ? JSON.parse(saved) : 'light'
  })

  // after every change: save it
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(theme))
  }, [theme])

The useState initializer reads localStorage once, on the first render. The effect saves every change. Nothing in those lines is about themes, though. A filter, a language or a draft message could be remembered the same way. So pull it out:

import { useEffect, useState } from 'react'

// a custom hook: a plain function that calls hooks,
// and its name starts with "use"
export function useLocalStorage<T>(
  key: string,
  initial: T,
) {
  // first render: read the saved value, if any
  const [value, setValue] = useState<T>(() => {
    const saved = localStorage.getItem(key)
    return saved ? (JSON.parse(saved) as T) : initial
  })

  // after every change: save it again
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value))
  }, [key, value])

  // give back the pair, just like useState
  return [value, setValue] as const
}

A custom hook is a plain function that calls hooks, and its name starts with use. The word theme became key, and light became initial. It returns the pair, so it feels exactly like useState. The Provider shrinks to one call:

// AFTER: the remembering is one hook call
export function ThemeProvider({ children }: Props) {
  const [theme, setTheme] =
    useLocalStorage<Theme>('theme', 'light')
  const toggle = () =>
    setTheme(theme === 'light' ? 'dark' : 'light')
  return (
    <ThemeContext value={{ theme, toggle }}>
      <div className={'app ' + theme}>{children}</div>
    </ThemeContext>
  )
}
provider: ThemeProvider + useLocalStorage
first load: button Dark mode
click: Dark mode
localStorage theme = "dark"
reload:     button Light mode

The same five lines as the inline version: same behaviour, much less code.

One hook, two separate states

import { useLocalStorage } from './useLocalStorage'

// one component, used twice: every call of the hook
// gets its OWN state (and here its own key)
function Draft({ to }: { to: string }) {
  const [text, setText] =
    useLocalStorage('draft-' + to, '')
  return (
    <label className="draft">
      Note to {to}
      <input
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
    </label>
  )
}

export function Drafts() {
  return (
    <section className="drafts">
      <Draft to="Emma" />
      <Draft to="Jack" />
    </section>
  )
}
Note to Emma: "" | Note to Jack: ""
type in box 1: Book the room
Note to Emma: "Book the room" | Note to Jack: ""
saved: draft-Emma = "Book the room", draft-Jack = ""

Each Draft calls the hook, and each call gets its own state slot. Typing in Emma's box changes only Emma's text. A hook shares the logic, never the state. If two components must share one value, that is a job for context.

The rules of hooks

React finds each hook by the order of the calls, not by name. The lecture's Note component puts a useState inside an if. After a click there are suddenly two hook calls instead of one:

render 1: 1 hook call
click: Open
React has detected a change in the order of Hooks called by Note. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useState                   useState
2. undefined                  useState
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Error: Rendered more hooks than during the previous render.

So: call hooks at the top level, never in an if, a loop or after an early return, and only in components and custom hooks. The same hooks, in the same order, on every render.

The whole app

import { ThemeProvider } from './ThemeContext'
import { UserProvider } from './UserContext'
import { Layout } from './Layout'

// two Providers: everything inside can read both
export default function App() {
  return (
    <ThemeProvider>
      <UserProvider>
        <Layout />
      </UserProvider>
    </ThemeProvider>
  )
}

Two Providers wrap the page, and Layout, Sidebar, UserBadge and ThemeToggle have no props between them. Providers wrap the part of the tree that needs the value, and the components inside just ask for it.

Recap

IdeaWhat to remember
Prop drillingValues passed through components that don't use them
createContext(default)Makes the context; the default is used only with no Provider above
ProviderGives a value to everything inside; the nearest one wins
useContextReads the value; readers re-render when it changes
Custom hookA use... function that calls hooks; each call has its own state
Rules of hooksTop level only, same order every render

Try it yourself: add a role line to UserBadge that shows Admin from the same context, and use useLocalStorage to remember which task was last clicked. Next: routing with React Router.

Keep going in React · 52 of 59

Previous
Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
Next post
Server State With TanStack Query: One Key, One Request, One Cache
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

React State, Events, Lists and Conditional Rendering: Follow One Click

Follow one click through a React counter, render by render: what useState hands back, why a plain variable never updates the page, ternaries and &&, map with keys, and the index-as-key bug that moves a typed note to the wrong task.

React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One

Watch useEffect on a timeline with real render counts: the dependency array deciding re-runs, a timer cleanup that keeps one timer alive, the leak StrictMode exposes, and two effects you should delete (a copied total and a click flag).

Lifting State Up, Refs and React DevTools: Put State Where It Is Needed

A task board where the filter is stuck in one component, fixed by lifting it to App. Then useRef as a box React does not watch (three clicks, zero renders), a ref that refocuses an input, and the tree React DevTools shows.

Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus

Four versions of an add-task form, traced with real logs: a controlled input, a classic onSubmit, a form action that gets FormData and resets itself, and useActionState with a pending button from useFormStatus, plus the draft trick that keeps typed text after an error.

On this page

  • Prop drilling: hop by hop
  • createContext and the Provider
  • useContext looks up the tree
  • The nearest Provider, or the default
  • The state lives in the Provider
  • Who re-renders when the value changes?
  • Remember the theme: from inline code to a custom hook
  • One hook, two separate states
  • The rules of hooks
  • The whole app
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.