Always manage the state at a component where every component that’s interested in it (parent component)
If a component below need to update the state, pass a callback handler down to it
If a component below need to use the state, pass it down as props
Callback Handler
A: Pass function from parent component to children component
B: Call function from children component as soon as state change via props
C: Actual implementation of function is in parent component
React props are always passed down as information the component tree, and callback handlers passed as functions in props can be used to communicate up the component hierarchy
Example
const App = () => {
const [searchTerm, setSearchTerm] = React.useState('');
// A - Pass function handleSearch() from parent component (BlogFeed) to children component (BlogSearch)
const handleSearch = event => {
// C - Actual implementation of function handleSearch() is in parent component (BlogFeed)
setSearchTerm(event.target.value);
}
return (
<BlogFeedWrap>
<h1>Blogs</h1>
<BlogSearch onSearch={handleSearch}/>
<BlogList list={blogs} />
</BlogFeedWrap>
);
}
const BlogSearch = props => {
return (
<BlogSearchWrap>
{/* B - Call function handleSearch() from children component (BlogSearch) as soon as input change via props */}
<SearchInput type='text' onChange={props.onSearch}></SearchInput>
<Button size='small'>Search</Button>
</BlogSearchWrap>
);
}
Lifting State
Callback Handler
Example