Lifting state up means moving shared data to a common parent so multiple parts can use it. It helps keep your app organized and data consistent.
Lifting state up in React Native
import React, { useState } from 'react'; function Parent() { const [sharedData, setSharedData] = useState(''); return ( <> <Child1 data={sharedData} onChange={setSharedData} /> <Child2 data={sharedData} /> </> ); }
The parent component holds the state using useState.
It passes the state and a function to update it down to children via props.
text state and passes it with a setter to Child.import React, { useState } from 'react'; function Parent() { const [text, setText] = useState(''); return <Child input={text} onInputChange={setText} />; }
count state with two children: one to change it, one to show it.import React, { useState } from 'react'; function Parent() { const [count, setCount] = useState(0); return ( <> <Incrementer count={count} onIncrement={() => setCount(count + 1)} /> <Display count={count} /> </> ); }
This app has a parent component holding the name state. The Input child lets the user type their name. The Greeting child shows a message using that name. Both children share the same state lifted up to the parent.
import React, { useState } from 'react'; import { View, Text, TextInput, StyleSheet } from 'react-native'; function Parent() { const [name, setName] = useState(''); return ( <View style={styles.container}> <Input name={name} onNameChange={setName} /> <Greeting name={name} /> </View> ); } function Input({ name, onNameChange }) { return ( <TextInput style={styles.input} placeholder="Enter your name" value={name} onChangeText={onNameChange} accessibilityLabel="Name input" /> ); } function Greeting({ name }) { return <Text style={styles.greeting}>Hello, {name || 'stranger'}!</Text>; } const styles = StyleSheet.create({ container: { padding: 20, marginTop: 50 }, input: { borderColor: '#888', borderWidth: 1, padding: 10, fontSize: 18, borderRadius: 5 }, greeting: { marginTop: 20, fontSize: 24, fontWeight: 'bold' } }); export default Parent;
Always lift state up to the closest common parent of components that need it.
Passing state down via props keeps data flow clear and predictable.
Use descriptive prop names like onChange or onNameChange for callback functions.
Lifting state up means moving shared data to a parent component.
This helps multiple components stay in sync and share data easily.
Use props to pass state and update functions down to children.