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

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Hooks

What you will learn

  • Spot when two sibling components need the same value
  • Lift state to the closest common parent: value down, change up
  • Use useRef for values that should not cause a render, and for page elements
  • Check props, hooks and renders with React DevTools

Before you start

  • React props and function props
  • useState and how a setter triggers a render

When two components need the same value, where should that value live? This article answers it with a small task board: three filter buttons (all, open, done), a card that lists the tasks, and a box to add a new one. In code that is TaskFilter, TaskList and AddTask, all inside App.

The filter bar knows which filter is picked. The list needs the same filter to decide which tasks to show. Let's see where the filter has to live, then meet refs, and check everything in React DevTools.

Two siblings, one value

The obvious first try keeps the filter in the component that changes it:

import { useState } from 'react'
import { start, type Filter } from '../tasks'
import TaskList from '../TaskList'

// BEFORE: the filter state is stuck in TaskFilter
function TaskFilter() {
  const [filter, setFilter] = useState<Filter>('all')
  console.log(`render: TaskFilter (${filter})`)
  return (
    <button onClick={() => setFilter('done')}>
      done
    </button>
  )
}

export default function StuckBoard() {
  console.log('render: StuckBoard')
  return (
    <div className="board">
      <TaskFilter />
      <TaskList tasks={start} filter="all" />
    </div>
  )
}
renders: StuckBoard, TaskFilter (all), TaskList
list: 5 of 5 shown
click: done
renders: TaskFilter (done)
list: 5 of 5 shown

Clicking done changes TaskFilter's own state, and only TaskFilter renders again. The list still says 5 of 5, because on line 21 it gets a fixed filter="all". It simply can't see the filter. And TaskFilter can't hand the value across: the two are siblings, and props only flow down from a parent to its children.

Lift the state up

The fix is to move the state to the closest parent both components can see. Here that is App:

import { useState } from 'react'
import { start, type Filter } from './tasks'
import TaskFilter from './TaskFilter'
import TaskList from './TaskList'
import AddTask from './AddTask'

export default function App() {
  // shared state: in the closest common parent
  const [filter, setFilter] = useState<Filter>('all')
  const [tasks, setTasks] = useState(start)
  console.log('render: App')

  function addTask(title: string) {
    const id = tasks.length + 1
    setTasks([...tasks, { id, title, done: false }])
  }

  return (
    <div className="board">
      <TaskFilter value={filter}
        onChange={setFilter} />
      <TaskList tasks={tasks} filter={filter} />
      <AddTask onAdd={addTask} />
    </div>
  )
}

Line 9 is the same useState, moved up. From App the value goes down: TaskList gets filter on line 22 and only reads it. TaskFilter gets two props on lines 20 and 21: value, the current filter, and onChange, which is setFilter itself.

A filter with no state

import type { Filter } from './tasks'

type Props = {
  value: Filter
  onChange: (next: Filter) => void
}
const FILTERS: Filter[] = ['all', 'open', 'done']

// no state here: the parent owns the value
function TaskFilter({ value, onChange }: Props) {
  console.log('render: TaskFilter')
  return (
    <div className="filters">
      {FILTERS.map((f) => (
        <button key={f}
          className={f === value ? 'on' : ''}
          onClick={() => onChange(f)}>
          {f}
        </button>
      ))}
    </div>
  )
}

export default TaskFilter

There is no useState here. The button whose name equals value gets the class on. A click calls onChange(f), which asks App and changes nothing locally. Forget to pass onChange in App and TypeScript stops the build:

TS2741: Property 'onChange' is missing in type '{ value: Filter; }' but required in type 'Props'.

A list that reads the filter

// does this task pass the filter?
export function matches(t: Task, filter: Filter) {
  if (filter === 'all') return true
  return filter === 'done' ? t.done : !t.done
}
type Props = { tasks: Task[]; filter: Filter }

// reads the filter, never changes it
function TaskList({ tasks, filter }: Props) {
  console.log('render: TaskList')
  const shown = tasks.filter((t) =>
    matches(t, filter))

  return (
    <div className="card">
      <p>{shown.length} of {tasks.length} shown</p>
      <ul>
        {shown.map((t) => (
          <li key={t.id}>
            {t.done ? '✔' : '○'} {t.title}
          </li>
        ))}
      </ul>
    </div>
  )
}

TaskList works out shown from its props on every render. With the filter set to done, Write report and Book flights pass, so it prints 2 of 5 shown.

Follow one click: up, then down

Events go up, data goes down App filter: "all" → "done" TaskFilter value, onChange TaskList 2 of 5 shown AddTask renders too onChange("done") filter="done"
The child calls the function it was given, and that function is App's setter. App renders again, and so does every component inside it.
renders: App, TaskFilter, TaskList, AddTask
list: 5 of 5 shown
click: done
renders: App, TaskFilter, TaskList, AddTask
list: 2 of 5 shown
rows: ✔ Write report | ✔ Book flights

Did AddTask need to render? Not really, nothing changed for it. But when a parent renders, every component inside it renders too. Keep that in mind for the DevTools part below.

A ref: a box React does not watch

import { useRef, useState } from 'react'

// counts in state: every click asks for a render
export function StateClicks() {
  const [clicks, setClicks] = useState(0)
  console.log('render: StateClicks')
  return (
    <button onClick={() => setClicks(clicks + 1)}>
      state: {clicks}
    </button>
  )
}

// counts in a ref: React does not watch the box
export function RefClicks() {
  const clicks = useRef(0)
  console.log('render: RefClicks')
  function add() {
    clicks.current += 1
    console.log('ref clicks =', clicks.current)
  }
  return (
    <button onClick={add}>
      ref: {clicks.current}
    </button>
  )
}

useRef(0) gives a small object, { current: 0 }, and returns the same box on every render. React does not watch it. Click the ref button three times, then let a parent render it again:

renders: RefClicks
ref clicks = 1
ref clicks = 2
ref clicks = 3
renders: none
page: ref: 0
renders: RefClicks
page: ref: 3

Three clicks, zero renders, and the page still says 0. The box holds 3, but nobody asked React to draw again. When a parent renders it, the new render reads the box and shows 3. Now the state button, clicked three times:

renders: StateClicks
click x3
renders: StateClicks, StateClicks, StateClicks
page: state: 3

Each click asks for a render, so state renders four times in total and shows 3. The rule that comes out of this: if the screen shows it, keep it in state. If only your code needs it, such as a timer id or a page element, a ref keeps it without a render.

A ref to an element

import { useRef } from 'react'

type Props = { onAdd: (title: string) => void }

function AddTask({ onAdd }: Props) {
  // a ref to the <input> element itself
  const inputRef = useRef<HTMLInputElement>(null)
  console.log('render: AddTask')
  function add() {
    const input = inputRef.current!
    if (!input.value.trim()) return
    onAdd(input.value.trim())
    input.value = ''
    input.focus() // cursor back in the box
  }

  return (
    <div className="add">
      <input ref={inputRef} placeholder="New task" />
      <button onClick={add}>add</button>
    </div>
  )
}

On the first render there is no input yet, so the box holds null. Line 19 attaches the ref, and after drawing React puts the real input element in inputRef.current. Type "Review budget" and click add:

renders: App, TaskFilter, TaskList, AddTask
type: Review budget
click: add
renders: App, TaskFilter, TaskList, AddTask
list: 6 of 6 shown
focus: <input>, value ""

The value goes up to App through onAdd (6 of 6 shown), the box is cleared, and focus() puts the cursor back for the next task.

Check it in React DevTools

React DevTools is a browser extension. Its Components tab shows the tree React keeps, with each component's props and hooks. The lecture prints the same tree with a small script after one click on done:

App
  hooks  State: "done" | State: Array(5)
  TaskFilter
    props  value: "done" | onChange: Æ’ bound dispatchSetState
  TaskList
    props  tasks: Array(5) | filter: "done"
  AddTask
    props  onAdd: Æ’ addTask
    hooks  Ref: {current: <input>}

The two State hooks live in App: the filter and the five tasks. TaskFilter has props only, and onChange shows as bound dispatchSetState, React's name for App's setter. TaskList reads tasks and filter. AddTask has onAdd plus one Ref hook holding the input.

In the DevTools settings, switch on "Highlight updates when components render". Click done and DevTools frames App, TaskFilter, TaskList and AddTask, the same four as in the render log. Click the ref button and nothing is framed, because nothing rendered.

Recap

IdeaWhat to remember
SiblingsCan't pass props sideways
Lifting state upMove it to the closest common parent; pass the value and the setter down
Data and eventsData goes down as props, changes go up through callbacks
useRefSame box every render; changing .current causes no render
Element refref={inputRef} lets your code call focus()
DevToolsComponents tab for props and hooks; highlight updates for renders

Try it yourself: add an "open" count above the list that reads the same lifted tasks state, and check in DevTools which components frame when you add a task. Next: forms and actions in React 19.

Keep going in React · 50 of 59

Previous
React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
Next post
Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
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).

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.

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.

On this page

  • Two siblings, one value
  • Lift the state up
  • A filter with no state
  • A list that reads the filter
  • Follow one click: up, then down
  • A ref: a box React does not watch
  • A ref to an element
  • Check it in React DevTools
  • 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.