0
0
Reactframework~30 mins

Sharing state between components in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Sharing state between components
📖 Scenario: You are building a simple React app that shows a counter. The counter value is shared between two components: one to display the count and one to increase it.This is like having a shared scoreboard where one person can see the score and another can update it.
🎯 Goal: Create two React functional components that share the same counter state. One component will show the current count, and the other will have a button to increase the count.
📋 What You'll Learn
Use React functional components
Use the useState hook to hold the counter value
Share the counter state between two components via props
Update the counter from the increment button component
Display the current counter value in the display component
💡 Why This Matters
🌍 Real World
Sharing state between components is common in React apps, like sharing user info or app settings across different parts of the UI.
💼 Career
Understanding how to share and update state between components is a key skill for React developers building interactive web apps.
Progress0 / 4 steps
1
Create the initial counter state
Create a React functional component called CounterApp. Inside it, create a state variable called count with initial value 0 using the useState hook.
React
Need a hint?

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

2
Create the display component
Inside CounterApp, create a new functional component called DisplayCount that accepts a prop called count and returns a <div> showing the text "Current count: " followed by the count value.
React
Need a hint?

Define DisplayCount inside CounterApp and use {count} inside the returned <div>.

3
Create the increment button component
Inside CounterApp, create a new functional component called IncrementButton that accepts a prop called onIncrement. It should return a <button> with the text "Increase". When clicked, it should call the onIncrement function.
React
Need a hint?

Use onClick={onIncrement} on the button inside IncrementButton.

4
Use the components and share state
Inside CounterApp's return statement, render <DisplayCount /> passing the count state as a prop, and <IncrementButton /> passing a function that increases count by 1 as the onIncrement prop.
React
Need a hint?

Use <DisplayCount count={count} /> and <IncrementButton onIncrement={() => setCount(count + 1)} /> inside the return.