Lifting State Up
Sometimes multiple components must reflect the same state change. In these instances, it is recommended that the state be lifted up to the nearest common ancestor.
Let's assume we want to create a progress bar with two control buttons. For this example, we will create an App component, a Progress component for the progress bar, a controls component, and a control button component.
function Progress (props) {
return (
<div className="progress">
<div
className="progress-bar"
role="progressbar"
style={{width: `${props.progress}%`}}
aria-label="Basic example"
aria-valuenow={props.progress}
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
)
}
function ControlButton (props) {
return (
<button className="btn btn-primary m-3">
{props.text}
</button>
)
}
function Controls (props) {
return (
<div className="d-flex justify-content-center">
<ControlButton text="-" />
<ControlButton text="+" />
</div>
)
}
function App () {
const [progress, setProgress] = React.useState(0)
return (
<React.Fragment>
<h2 className="display-4 text-center">{progress}</h2>
<Progress progress={progress} />
<Controls progress={progress} />
</React.Fragment>
)
}