In React, “props” and “state” are essential concepts used for managing data and rendering components dynamically.
Props
- Definition: Short for “properties”, props are read-only attributes used to pass data from a parent component to a child component.
- Characteristics:
- Immutable: Once passed, props cannot be changed by the child component.
- Pure Data: Props are used purely to pass data and cannot maintain any internal state.
- Unidirectional Flow: Data flows from parent to child, maintaining a one-way data binding.
Usage:
// ParentComponent.jsx
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const data = "Hello from Parent!";
return ;
}
export default ParentComponent;
// ChildComponent.jsx
import React from 'react';
function ChildComponent(props) {
return {props.message};
}
export default ChildComponent;
State
- Definition: State is an object that holds dynamic data and determines how the component renders and behaves.
- Characteristics:
- Mutable: State can be changed over time, usually in response to user actions or other events.
- Local: State is managed within the component, but can be passed down to child components via props.
- Triggers Re-renders: Updating the state causes the component to re-render, reflecting the new state.
Usage (using React Hooks):
import React, { useState } from 'react';
function StatefulComponent() {
// Declare a state variable named 'count' with an initial value of 0
const [count, setCount] = useState(0);
return (
Count: {count}
);
}
export default StatefulComponent;