Sharing state lets different parts of your app use the same information. This keeps everything in sync and working together smoothly.
Sharing state between components in React
const [state, setState] = useState(initialValue); // Pass state and setState as props to child components <ChildComponent state={state} setState={setState} />
Use useState hook to create state in a parent component.
Pass both the state and the function to update it (setState) to child components via props.
function Parent() { const [count, setCount] = React.useState(0); return <Child count={count} setCount={setCount} />; } function Child({ count, setCount }) { return <button onClick={() => setCount(count + 1)}>{count}</button>; }
text state with two children: one to update it and one to show it.function Parent() { const [text, setText] = React.useState(''); return ( <> <Input text={text} setText={setText} /> <Display text={text} /> </> ); } function Input({ text, setText }) { return <input value={text} onChange={e => setText(e.target.value)} />; } function Display({ text }) { return <p>You typed: {text}</p>; }
This app shares the color state between a dropdown to pick a color and a text that shows the chosen color in that color. Changing the dropdown updates the text color instantly.
import React, { useState } from 'react'; export default function SharingState() { const [color, setColor] = useState('red'); return ( <main> <h1>Pick a color:</h1> <ColorPicker color={color} setColor={setColor} /> <ColorDisplay color={color} /> </main> ); } function ColorPicker({ color, setColor }) { return ( <select aria-label="Choose color" value={color} onChange={e => setColor(e.target.value)}> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select> ); } function ColorDisplay({ color }) { return <p style={{ color: color, fontWeight: 'bold' }}>You selected: {color}</p>; }
Always keep the shared state in the closest common parent of the components that need it.
Passing state and updater as props is simple and works well for small apps.
For bigger apps, consider React Context or state management libraries to share state more easily.
Sharing state means keeping data in one place and letting components use it.
Use useState in a parent and pass state and updater to children via props.
This keeps your app consistent and easier to understand.