0Pricing
React Native Academy · Leçon

Remonter l’état

Déplacez l’état partagé vers l’ancêtre commun le plus proche et transmettez à vos composants frères, via les props, à la fois la valeur et une fonction de rappel de mise à jour afin de les maintenir synchronisés.

Remonter l’état est une leçon React Native Academy gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage React Native Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours React Native Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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.

Questions Fréquemment Posées

La leçon « Remonter l’état » est-elle gratuite ?

Oui — le texte complet de « Remonter l’état » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours React Native Academy, passe à CoddyKit PRO. Le cours React Native Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Remonter l’état » ?

Déplacez l’état partagé vers l’ancêtre commun le plus proche et transmettez à vos composants frères, via les props, à la fois la valeur et une fonction de rappel de mise à jour afin de les maintenir… Tu pratiques React Native Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer React Native Academy ?

Aucune expérience préalable n'est requise. React Native Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.

Combien de temps prend la leçon « Remonter l’état » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon React Native Academy ?

Oui. Chaque leçon React Native Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Transmettre des données avec les props
  2. Gérer l’état d’un composant avec useState
  3. Remonter l’état
  4. Construire une application de compteur interactive
← Retour à React Native Academy