상태 끌어올리기
공유 상태를 가장 가까운 공통 상위 컴포넌트로 옮기고 값과 업데이트 콜백을 모두 props로 전달하여 형제 컴포넌트의 상태를 동기화합니다.
상태 끌어올리기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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.
자주 묻는 질문
“상태 끌어올리기” 강의는 무료인가요?
네 — “상태 끌어올리기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“상태 끌어올리기”에서 뭘 배우나요?
공유 상태를 가장 가까운 공통 상위 컴포넌트로 옮기고 값과 업데이트 콜백을 모두 props로 전달하여 형제 컴포넌트의 상태를 동기화합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
React Native Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“상태 끌어올리기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.