Quiz 1152: React State vs Props
What's the difference between state and props in React?
Quick Answer
In React, props are used to pass data from a parent component to a child component. They're like read-only inputs for a component. State is internal data managed by the component itself, allowing it to change and trigger re-renders.
Explain in Depth
Props (Properties)
-
Purpose: Props are used to pass data from a parent component to its child component. They are like read-only inputs for the child component.
-
Mutability: Props are immutable, meaning they cannot be modified directly by the child component.
-
Data Flow: Data flows in a unidirectional manner from parent to child using props.
-
Example:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } function App() { return ( <div> <Welcome name="John" /> </div> ); }
In this example,
name
is a prop passed from theApp
component to theWelcome
component.
State
-
Purpose: State represents internal data managed by a component. It's used to track the component's current state and trigger re-renders when the state changes.
-
Mutability: State is mutable, meaning it can be modified by the component itself using the
setState
method. -
Data Flow: State changes are managed within the component itself.
-
Example:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Counter;
Here,
count
is the component's state, and thesetCount
function updates the state when the button is clicked, triggering a re-render and updating the count display.
Key Differences:
Feature | Props | State |
---|---|---|
Purpose | Data from parent to child | Internal data managed by the component |
Mutability | Immutable (read-only for the child) | Mutable |
Data Flow | Unidirectional (parent to child) | Managed within the component |
In summary, props are used to pass data into a component, while state is used to manage the component's internal data and trigger updates. Understanding the difference between these concepts is crucial for managing data flow and building complex, interactive React applications.