0
0
Reactframework~30 mins

Common lifting state patterns in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Common Lifting State Patterns in React
📖 Scenario: You are building a simple React app where two sibling components need to share and update the same data. This is a common situation where lifting state up helps keep data consistent.
🎯 Goal: Build two sibling components that share a counter value. The counter state should live in their common parent. One sibling increments the counter, and the other displays the current count.
📋 What You'll Learn
Create a parent component called CounterParent with a state variable count initialized to 0
Create a child component called Incrementer that has a button to increase count by 1
Create a child component called DisplayCount that shows the current count value
Lift the count state up to CounterParent and pass necessary props to children
💡 Why This Matters
🌍 Real World
Many React apps need multiple components to share and update the same data. Lifting state up is a simple and common pattern to keep data consistent and synchronized.
💼 Career
Understanding lifting state is essential for React developers to build maintainable and scalable user interfaces where components communicate effectively.
Progress0 / 4 steps
1
Create the parent component with initial state
Create a React functional component called CounterParent. Inside it, use useState to create a state variable called count initialized to 0. Return a div with the text Parent Component.
React
Need a hint?

Use const [count, setCount] = useState(0); inside the CounterParent function.

2
Add child components Incrementer and DisplayCount
Inside the same file, create two new functional components: Incrementer and DisplayCount. For now, have Incrementer return a button with text Increment. Have DisplayCount return a div with text Count: 0. Update CounterParent to render both components inside a div.
React
Need a hint?

Define two new functions Incrementer and DisplayCount that return the specified JSX elements.

3
Lift state: Pass count and setCount as props
Modify CounterParent to pass count as a prop named count to DisplayCount. Pass setCount as a prop named setCount to Incrementer. Update DisplayCount to accept count as a prop and display it inside the div. Update Incrementer to accept setCount as a prop and add an onClick handler to the button that calls setCount with count => count + 1.
React
Need a hint?

Pass props from CounterParent and use them inside the child components.

4
Add accessibility and final touches
Add an aria-label attribute with value Increment counter to the button in Incrementer for accessibility. Wrap the two child components inside a section element with aria-live="polite" in CounterParent to announce count changes to screen readers.
React
Need a hint?

Use aria-label on the button and wrap children in a section with aria-live="polite".