Props and State in React
1. Props (Properties)
Props are inputs to a React component. They are read-only and allow data to be passed from a parent component to a child component. Props make components reusable and dynamic, as they can be configured with different data each time they are used.
Think of props as arguments passed to a function. Just as a function can perform different tasks based on its arguments, a React component can render different content based on its props.
Example of Props:
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } function App() { return ( <div> <Greeting name="Alice" /> <Greeting name="Bob" /> </div> ); }
In this example, the Greeting
component receives a name
prop and displays a personalized greeting. The App
component uses the Greeting
component twice with different names.
2. State
State is a built-in object in React that stores data that can change over time. When the state changes, React re-renders the component to reflect the new state. State is used to manage dynamic data within a component.
Think of state as the memory of a component. Just as a person's memory can change over time, a component's state can change in response to user interactions or other events.
Example of State:
function Counter() { const [count, setCount] = React.useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
In this example, the Counter
component has a state variable count
initialized to 0. When the button is clicked, the state is updated, and the component re-renders to display the new count.
Analogies
Props: Imagine a recipe book. Each recipe (component) can be made with different ingredients (props). For example, a "Pizza" recipe can be made with different toppings like "Pepperoni" or "Mushroom". The recipe remains the same, but the outcome (rendered component) changes based on the ingredients.
State: Think of a thermostat. The temperature (state) can change based on user input (e.g., turning the dial). When the temperature changes, the thermostat (component) updates to display the new temperature. Similarly, in React, when the state changes, the component re-renders to reflect the new state.