0Pricing
React Native Academy · Lesson

Lifting State Up

Move shared state to the nearest common ancestor and pass both the value and an updater callback as props to keep sibling components in sync.

Lifting State Up is a free React Native Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Native Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Problem: Siblings Need Shared State

Imagine two sibling components that need to share a piece of data — for example, a search input component and a results list that filters based on that search query. If the search state lives inside the search input component, the results list has no way to access it. Neither sibling can see each other's state directly. The solution is to lift the state up to the nearest common ancestor — the parent component that renders both siblings. The parent then passes the state value to one child and the setter callback to the other.

// PROBLEM: SearchInput holds state that ResultsList needs
// but siblings can't communicate directly

function SearchInput() {
  const [query, setQuery] = useState(''); // stuck here
  return <TextInput value={query} onChangeText={setQuery} />;
}

function ResultsList() {
  // How do we access 'query' from the sibling? We can't!
  return <FlatList data={/* needs query */} />;
}

Lifting State to the Common Ancestor

Move the shared state to the closest common ancestor — the component that renders both siblings. The parent now owns the state and passes it down as props: the search query goes to the results list, and the setter function goes to the search input. The siblings communicate through the parent: the search input calls the setter (passed as a prop), which updates the parent's state, which flows the new query value to the results list as a new prop. This is the fundamental React data flow pattern.

import { useState } from 'react';
import { View, TextInput, Text } from 'react-native';

// Parent owns the shared state
export default function SearchScreen() {
  const [query, setQuery] = useState('');
  const results = ITEMS.filter(item =>
    item.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <View style={{ flex: 1, padding: 16 }}>
      <SearchInput query={query} onQueryChange={setQuery} />
      <ResultsList results={results} />
    </View>
  );
}

const ITEMS = ['Apple', 'Banana', 'Blueberry', 'Cherry', 'Avocado'];

Writing the Child Components

With lifted state, the child components become simple and focused. The SearchInput component receives query (current value) and onQueryChange (to update it) as props. The ResultsList receives the filtered results array. Neither child manages state — they are controlled components whose behavior is entirely driven by their props. This makes both components easy to test in isolation: just pass the props and assert the rendered output.

import { TextInput, FlatList, Text, View, StyleSheet } from 'react-native';

// Controlled: receives value and updater as props
function SearchInput({ query, onQueryChange }) {
  return (
    <TextInput
      value={query}
      onChangeText={onQueryChange}
      placeholder='Search...'
      style={styles.input}
    />
  );
}

// Pure display: receives filtered data as prop
function ResultsList({ results }) {
  return (
    <FlatList
      data={results}
      keyExtractor={item => item}
      renderItem={({ item }) => (
        <Text style={styles.item}>{item}</Text>
      )}
    />
  );
}

const styles = StyleSheet.create({
  input: { borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 12, marginBottom: 12 },
  item: { padding: 12, borderBottomWidth: 1, borderBottomColor: '#eee' },
});

Finding the Nearest Common Ancestor

The key question when lifting state is: 'Which is the lowest component in the tree that renders all the components needing this state?' Lift state to exactly that component — no higher. Lifting too high (e.g., all the way to App) causes unnecessary re-renders of unrelated components. The nearest common ancestor is the right balance between accessibility (all consumers can receive the state as props) and performance (only the subtree that needs the state re-renders). Draw your component tree and trace upward from each consumer to find where paths converge.

// Component tree:
// App
// └── TabBar (selected tab)
//     ├── HomeTab
//     │   └── Feed
//     └── ProfileTab
//
// If 'selected tab' is needed by TabBar AND by Feed to filter content,
// lift it to TabBar (nearest common ancestor of both).
// DO NOT lift all the way to App unnecessarily.

function TabBar() {
  const [activeTab, setActiveTab] = useState('home');
  return (
    <View>
      <TabButtons activeTab={activeTab} onChange={setActiveTab} />
      {activeTab === 'home' ? <HomeTab /> : <ProfileTab />}
    </View>
  );
}

Multiple Siblings Sharing State

When three or more siblings need the same state, lift it once to their shared parent and pass it to each sibling that needs it. For example, a product detail screen might have an ImageGallery, a VariantPicker, and an AddToCartButton. The selected variant state lives in the parent screen component and flows to all three. VariantPicker gets the setter to change the selection. ImageGallery shows images for the selected variant. AddToCartButton adds the specific selected variant to the cart.

import { useState } from 'react';
import { View } from 'react-native';

const VARIANTS = ['Red / S', 'Red / M', 'Blue / S', 'Blue / M'];

export default function ProductDetailScreen() {
  const [selectedVariant, setSelectedVariant] = useState(VARIANTS[0]);

  return (
    <View style={{ flex: 1 }}>
      <ImageGallery variant={selectedVariant} />
      <VariantPicker
        variants={VARIANTS}
        selected={selectedVariant}
        onSelect={setSelectedVariant}
      />
      <AddToCartButton variant={selectedVariant} />
    </View>
  );
}

Callback Props vs. Shared State

Sometimes components share an action rather than a state value. A common example: a list screen with a cart icon in the header — pressing 'Add to Cart' on any list item should update the badge count in the header. Both the list items and the header are siblings under the same parent screen. The parent holds the cart count in state, passes the count to the header via props, and passes an onAddToCart callback to the list. Items call the callback; the parent updates its state; the header badge re-renders with the new count.

import { useState } from 'react';
import { View } from 'react-native';

export default function ShopScreen() {
  const [cartCount, setCartCount] = useState(0);

  function addToCart(item) {
    // Business logic lives in the parent
    setCartCount(prev => prev + 1);
    console.log('Added:', item.name);
  }

  return (
    <View style={{ flex: 1 }}>
      {/* Sibling 1: displays count from parent state */}
      <ShopHeader cartCount={cartCount} />
      {/* Sibling 2: triggers parent state update */}
      <ProductList onAddToCart={addToCart} />
    </View>
  );
}

When Lifting State Becomes Prop Drilling

If the common ancestor is many levels above the components that need the state, you end up with prop drilling — passing props through many intermediate components that don't use them. For example, if the common ancestor is the App root and there are 5 component levels between App and the consumers, every intermediate component becomes a messenger. The solution for deep sharing is Context API (for data that many components need) or a state management library like Zustand or Redux. The rule of thumb: lift state, but if it crosses more than 2–3 levels without being used in between, consider Context instead.

// When prop drilling gets too deep, switch to Context
// Instead of:
function App() {
  const [user, setUser] = useState(null);
  return <Nav user={user}>   // not used
    <Drawer user={user}>     // not used
      <Screen user={user}>  // not used
        <ProfileCard user={user} />  // finally used
      </Screen>
    </Drawer>
  </Nav>;
}

// Use Context:
const UserContext = React.createContext(null);
function App() {
  const [user, setUser] = useState(null);
  return (
    <UserContext.Provider value={user}>
      <Nav><Drawer><Screen><ProfileCard /></Screen></Drawer></Nav>
    </UserContext.Provider>
  );
}

Practical Example: Temperature Converter

A classic demonstration of lifting state: two temperature input fields (Celsius and Fahrenheit) that stay in sync. Each input field takes the current temperature and an onChange callback. The parent holds the temperature in one unit (say Celsius) and converts it for the other input. When either input changes, the parent converts and updates its state. Both inputs receive the correct value from parent state, keeping them perfectly synchronized through the shared parent state.

import { useState } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

function TempInput({ label, value, onChangeText }) {
  return (
    <View style={styles.row}>
      <Text style={styles.label}>{label}</Text>
      <TextInput
        value={value}
        onChangeText={onChangeText}
        keyboardType='decimal-pad'
        style={styles.input}
      />
    </View>
  );
}

export default function TemperatureConverter() {
  const [celsius, setCelsius] = useState('');

  const fahrenheit = celsius !== '' ? (parseFloat(celsius) * 9/5 + 32).toFixed(1) : '';

  function handleFahrenheitChange(f) {
    const c = f !== '' ? ((parseFloat(f) - 32) * 5/9).toFixed(1) : '';
    setCelsius(c);
  }

  return (
    <View style={{ padding: 24 }}>
      <TempInput label='Celsius' value={celsius} onChangeText={setCelsius} />
      <TempInput label='Fahrenheit' value={fahrenheit} onChangeText={handleFahrenheitChange} />
    </View>
  );
}

const styles = StyleSheet.create({
  row: { flexDirection: 'row', alignItems: 'center', marginBottom: 12 },
  label: { width: 100, fontSize: 16 },
  input: { flex: 1, borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 10 },
});

Collocate State Close to Where It's Used

The mirror principle to lifting state is keeping state as low as possible. If only one component needs a piece of state, keep it inside that component — don't lift it unnecessarily. For example, a dropdown's open/closed state doesn't need to be in the parent screen unless the parent needs to react to it. Keeping local state local improves performance (fewer components re-render) and makes code easier to reason about (state and the UI that uses it are in the same place). Only lift when two or more components truly need the same data.

// Local state: Accordion open/close is private to Accordion
function Accordion({ title, children }) {
  const [open, setOpen] = useState(false); // stays local — parent doesn't care
  return (
    <View>
      <TouchableOpacity onPress={() => setOpen(prev => !prev)}>
        <Text>{title} {open ? '▲' : '▼'}</Text>
      </TouchableOpacity>
      {open && <View style={{ paddingLeft: 16 }}>{children}</View>}
    </View>
  );
}

// Only lift open state to parent IF the parent needs to:
// - Know which accordion is open to close others
// - Save/restore the open state on navigation
// Otherwise, keep it local!

Uncontrolled vs. Controlled Components

A component is controlled when its state is driven entirely by props (and changed via callbacks) — like the search input example. It is uncontrolled when it manages its own internal state without exposing it to the parent. Most of the time in React, you use controlled components because they are predictable and easy to test. Uncontrolled inputs (using ref to read values) are used occasionally for performance (avoiding re-renders on every keystroke) or for integrating with non-React code. The default form elements in React Native's TextInput are controlled when you pass value and onChangeText.

import { TextInput, useRef } from 'react-native';

// Uncontrolled: parent reads value on demand via ref
function UncontrolledInput({ inputRef }) {
  return (
    <TextInput
      ref={inputRef}
      // No value prop: TextInput manages its own text
      defaultValue='Initial text'
    />
  );
}

// Parent reads the value when the form is submitted:
function Form() {
  const inputRef = useRef(null);
  function handleSubmit() {
    // Use _lastNativeText (not recommended) or store value in ref.current
    console.log('Value:', inputRef.current?.props?.value);
  }
}

Real-World: Filter and Results Panel

A practical application of lifted state: a search screen with a filter bar (category selector, price range slider, sort picker) above a results list. Each filter value lives in the parent SearchScreen component. The filter bar receives current filter values and setter callbacks as props. The results list receives the current filters and re-renders whenever any filter changes. The parent also fetches new results whenever filters change (via useEffect on filter dependencies). This coordination through a single parent makes the search feature predictable and easy to test.

import { useState, useEffect } from 'react';
import { View } from 'react-native';

export default function SearchScreen() {
  // All filter state lifted here
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState('all');
  const [sortBy, setSortBy] = useState('relevance');
  const [results, setResults] = useState([]);

  // Fetch results whenever any filter changes
  useEffect(() => {
    fetchResults({ query, category, sortBy }).then(setResults);
  }, [query, category, sortBy]);

  return (
    <View style={{ flex: 1 }}>
      <FilterBar
        query={query} onQueryChange={setQuery}
        category={category} onCategoryChange={setCategory}
        sortBy={sortBy} onSortChange={setSortBy}
      />
      <ResultsList results={results} />
    </View>
  );
}

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: lifting state to the nearest common ancestor allows siblings to share data through their parent, controlled components receive their value and updater as props making them predictable and testable, and state should stay as low as possible — only lift it when multiple components truly need it. Next up we build an interactive counter app combining all of these concepts.

Frequently asked questions

Is the “Lifting State Up” lesson free?

Yes — the full text of “Lifting State Up” is free to read here on the web, and the React Native Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Native Academy course, upgrade to CoddyKit PRO.

What will I learn in “Lifting State Up”?

Move shared state to the nearest common ancestor and pass both the value and an updater callback as props to keep sibling components in sync. You practise React Native Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Native Academy?

No prior experience is required. React Native Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Lifting State Up” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Native Academy lesson?

Yes. Every React Native Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Passing Data with Props
  2. Managing Component State with useState
  3. Lifting State Up
  4. Building an Interactive Counter App
← Back to React Native Academy