0
0
Reactframework~15 mins

What is state in React - Hands-On Activity

Choose your learning style9 modes available
What is state
📖 Scenario: You want to build a simple React component that shows a number on the screen. This number can change when you click a button. To do this, you need to keep track of the number inside the component. This is called state.
🎯 Goal: Create a React functional component that uses state to store a number. Add a button that, when clicked, increases the number by 1. The number should update on the screen each time you click the button.
📋 What You'll Learn
Use React functional component
Use the useState hook to create a state variable called count
Initialize count to 0
Add a button with an onClick event that increases count by 1
Display the current value of count in a <div>
💡 Why This Matters
🌍 Real World
Tracking user interactions like clicks, form inputs, or toggles in a web app.
💼 Career
Understanding state is essential for building interactive React applications used in many web development jobs.
Progress0 / 4 steps
1
Set up the React component and initial state
Create a React functional component called Counter. Inside it, use the useState hook to create a state variable named count and a setter function named setCount. Initialize count to 0.
React
Need a hint?

Remember to import useState from React. Use const [count, setCount] = useState(0); inside the component.

2
Add a button to increase the count
Inside the Counter component, return a <button> element. Add an onClick event to the button that calls setCount(count + 1) to increase the count by 1 when clicked.
React
Need a hint?

Use onClick={() => setCount(count + 1)} inside the button tag.

3
Display the current count value
Modify the returned JSX to include a <div> that shows the current value of count above the button.
React
Need a hint?

Use a <div> with {count} inside the returned JSX.

4
Complete the component export
Add export default Counter; at the end of the file to make the component usable in other parts of the app.
React
Need a hint?

Write export default Counter; at the end of the file.