Skip to content
engineering workbench.by StudyPort Academy
Learning path
Intermediate22 minLESSON 05 / 8

Sharing state

01

Understand the idea

If two components must show the same value, that value should live in one place — usually their closest shared parent — and be passed down.

Lift state to the parent

Suppose two sibling components both need the same name. If each calls its own useState, they will drift apart as soon as either one updates.

The fix is usually simple: move the useState into the parent that renders both. Pass the value down as a . Pass a setter or an onChange callback down if the child needs to request a change.

That is “lifting state up.” Do this before you reach for a bigger tool.

Context when props travel too far

Sometimes the parent is many layers above the child, and middle components only exist to pass props through. Context lets a child read a value from the nearest Provider without every layer naming that prop.

Create a context, wrap a subtree in Provider, and call useContext in a child. Theme and “current user” are common examples.

Context is not automatically “global state for everything.” A Provider value that changes re-renders consumers. Start with props; use context when drilling becomes the problem.

Where a value can live
ToolUse it whenAvoid it when
propsOne or two levels need the valueYou are threading it through many indifferent layers
contextMany descendants need the same valueThe value changes every animation frame
refYou need a DOM node or a mutable boxThe screen must update when it changes
reducerUpdates have clear names and rulesYou only have one boolean

Refs and a small reducer

useRef returns an object with a current property. Changing current does not re-render. That is useful for a DOM node (attach the ref to an input) or for a value a timer must see without restarting every render.

useReducer is an alternative to useState when the next value depends on an “action,” such as rename. You write a reducer function: given state and action, return the next state. The component calls dispatch with that action instead of many different setters.

One custom hook in the example

In the live example, useShift wraps useReducer. App calls useShift, gets shift and dispatch, and renders the name. Child reads a separate context value with useContext. The console labels name the five ideas: lifted, context, ref, reducer, custom-hook.

You do not need all five tools in every file. The lesson shows them in one place so you can recognize each pattern.

Choose the smallest tool that works

  1. Props and a parent useState.
  2. Context if prop drilling is the pain.
  3. Reducer if the update rules are getting hard to follow.
  4. A custom if the same block appears in more than one component.
  5. A ref when you need a mutable box without rendering.
02

Mental model

FOLLOW THE VALUE

two children
parent state
props down

The parent owns the value.

01 / 03Trace the transformation

03

Live example

The example shows one parent that owns shift state, provides a context value, keeps a ref, and uses a small custom hook. The console names each of those tools.

import { createContext, useContext, useReducer, useRef } from "react";
const ShiftContext = createContext("day"); // A value many descendants can read.
function reducer(state, action) {
  if (action.type === "rename") return { ...state, name: action.name }; // Pure transition.
  return state;
}
function useShift(initial) {
  return useReducer(reducer, initial); // Custom hook wraps the reducer.
}
export default function App() {
  const [shift, dispatch] = useShift({ name: "Ada" }); // Shared shift state.
  const inputRef = useRef(null); // Mutable box that does not re-render.
  console.log("lifted"); // Parent owns the shared value.
  console.log("context"); // Context skips prop drilling.
  console.log("ref"); // Ref holds a node or mutable value.
  console.log("reducer"); // Reducer names each update.
  console.log("custom-hook"); // A hook reuses the pattern.
  return (
    <ShiftContext.Provider value="day"> {/* Publish to descendants. */}
      <p>{shift.name}</p>
      <Child />
      <input ref={inputRef} defaultValue={shift.name} /> {/* Attach the DOM node. */}
      <button type="button" onClick={() => dispatch({ type: "rename", name: "Ada" })}>Rename</button>
    </ShiftContext.Provider>
  );
}
function Child() {
  const shiftName = useContext(ShiftContext); // Read the nearest provider.
  return <p>{shiftName}</p>;
}

VISUAL FLOW

Try the same flow interactively

Shared values live in one owner. Props or context deliver them. Children request changes; they do not keep a second copy.

Step 1 of 5

Click through ownership → context → update

owner

App

name

Ada

Parent owns the shared value

const [shift, dispatch] = useShift({ name: "Ada" });

The parent keeps the record. Siblings do not each call their own useState for the same name.

04

Guided challenge

Name the shared owner

The log says copy. Change it to lifted, the state that one parent owns for both children.

export default function App() {
  console.log("copy"); // Wrong - change this to lifted.
  console.log("context"); // Keep the context log.
  console.log("ref"); // Keep the ref log.
  console.log("reducer"); // Keep the reducer log.
  console.log("custom-hook"); // Keep the custom-hook log.
  return <p>copy</p>;
}

EXPECTED CONSOLE OUTPUT

lifted
context
ref
reducer
custom-hook

Hints 0/2

    05

    Free sandbox

    Make a variation, test an assumption, or break the example on purpose. This draft is saved separately.

    import { useState } from "react";
    export default function App() {
      const [name, setName] = useState("Ada"); // Lifted into the parent.
      return (
        <div>
          <input value={name} onChange={(event) => setName(event.target.value)} /> {/* Parent updates. */}
          <Preview name={name} /> {/* Child only reads the prop. */}
        </div>
      );
    }
    function Preview({ name }) {
      return <p>{name}</p>; // Display what the parent owns.
    }
    
    
    06

    Quiz

    A quick check for understanding. Retry as often as you like; your learning path stays open.

    01Where should state live if two siblings both display it?
    02What does useRef give you that useState does not?

    Ready to call this one understood?

    Mark this lesson complete to earn 150 XP. You can always revisit it.

    Sign in to save progress
    Next lesson