Props and State in React
Understand how React components communicate and manage data with props and state.
1. What are Props?
Props (short for "properties") are a mechanism for passing data from a parent component to a child component in React. They are immutable, meaning they cannot be changed by the receiving component.
Example:
function Greeting(props) { returnHello, {props.name}!
; } function App() { return; }
Explanation: The App
component passes the name
prop to the Greeting
component, which renders "Hello, Alice!"
2. What is State?
State is a special object in React components used to manage dynamic data. Unlike props, state is mutable and controlled internally by the component.
Example of state in a class component:
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return (); } }Count: {this.state.count}
Explanation: The Counter
component manages a count
state that updates when the button is clicked.
3. Using State in Functional Components
With the introduction of hooks in React 16.8, state can be managed in functional components using the useState
hook.
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return (); }Count: {count}
Explanation: The useState
hook initializes the count
state to 0 and provides a function setCount
to update it.
4. Key Differences Between Props and State
Props | State |
---|---|
Passed from parent to child components. | Managed internally by the component. |
Immutable (cannot be changed). | Mutable (can be updated). |
Used for read-only data. | Used for dynamic, interactive data. |
5. Combining Props and State
Props and state often work together to create dynamic, interactive components:
function Greeting({ name }) { returnHello, {name}!
; } function App() { const [name, setName] = React.useState("John"); return (); }
Explanation: The name
state is managed by the parent App
component and passed to the child Greeting
component as a prop.
6. Best Practices
- Use props for passing static or parent-controlled data to child components.
- Use state for managing dynamic or interactive data that belongs to a component.
- Avoid lifting state unnecessarily; keep state as close to where it’s needed as possible.