Props
Props (short for properties) are used to pass data from one component to another, typically from a parent component to a child component. Props are read-only, which means a child component cannot modify the props it receives.
import React from 'react';
// Child component
function Child(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Parent component
function App() {
return (
<div>
<Child name="Alice" />
<Child name="Bob" />
</div>
);
}
export default App;
Destructuring Props:
function Child({ name }) {
return <h1>Hello, {name}!</h1>;
}
Key Points:
- Read-Only: Props are immutable; the child component cannot modify them.
- Passed Down: Props are passed from parent to child components.
- Destructuring: Props can be destructured for cleaner code.
State
State represents data that can change over time. Unlike props, state is managed within the component and can be updated. In functional components, state is managed using the useState
hook.
import React, { useState } from 'react';
function Counter() {
// Declare a state variable "count" with an initial value of 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Counter;
In this Example:
The useState
hook is used to create a state variable count
and a function setCount
to update it.
The component re-renders whenever setCount
is called with a new value.
When the new state depends on the previous state, use the functional form of the state updater:
setCount(prevCount => prevCount + 1);
Key Points
- Mutable: State can be changed using the updater function returned by useState.
- Hook Usage: The useState hook is used to add state to functional components.
- Re-renders: Updating the state causes the component to re-render and reflect the new state.
Differences Between State and Props:
State | Props |
Managed within the component. | Passed from parent to child. |
Mutable using the useState hook. | Read-only (immutable within the child component). |
Used for data that changes over time and affects rendering. | Used to pass data and event handlers down the component tree. |