0
0
Reactframework~30 mins

State vs props comparison in React - Hands-On Comparison

Choose your learning style9 modes available
State vs Props Comparison in React
📖 Scenario: You are building a simple React app that shows a user's name and allows changing it inside a child component. This will help you understand the difference between state and props.
🎯 Goal: Create a React app with a parent component that holds a user's name in state. Pass the name as props to a child component. The child component will display the name and have a button to change it by calling a function passed as props.
📋 What You'll Learn
Use React functional components with hooks
Create a Parent component with a name state variable
Pass name and a function to update it as props to Child
In Child, display the name from props
Add a button in Child that changes the name by calling the passed function
💡 Why This Matters
🌍 Real World
Managing state and passing props is fundamental in React apps for building interactive user interfaces.
💼 Career
Understanding state vs props is essential for React developers to build maintainable and scalable components.
Progress0 / 4 steps
1
Create Parent component with name state
Create a React functional component called Parent. Inside it, use useState to create a state variable called name with initial value "Alice". Export the Parent component.
React
Need a hint?

Use const [name, setName] = useState("Alice") inside the Parent function.

2
Add Child component and pass props
Inside the Parent component, create a Child component that accepts name and changeName as props. Render Child inside Parent and pass name and setName as changeName prop.
React
Need a hint?

Define Child as a function with { name, changeName } props. Render <Child name={name} changeName={setName} /> inside Parent.

3
Display name and add button in Child
In the Child component, display the name prop inside a <p> tag. Add a <button> that when clicked calls changeName with the value "Bob".
React
Need a hint?

Use <p>{name}</p> to show the name. Add a button with onClick={() => changeName("Bob")}.

4
Export Child and finalize Parent rendering
Export the Child component. In the Parent component, wrap the Child component inside a <main> tag for semantic HTML.
React
Need a hint?

Use export function Child and wrap <Child /> inside <main> in Parent.