Props and State in React

Expert-Level Explanation

In React, props (short for properties) and state are two core concepts that manage data.

  • Props: Props are read-only and allow you to pass data from a parent component to a child component. They are similar to function arguments and are used to communicate between components, making them dynamic and reusable. Props are immutable within the component that receives them.

  • State: State is local data storage that is specific to a component and can change over time. It is used for data that a component needs to handle internally. When the state of a component changes, the component re-renders to reflect those changes. The state is mutable and managed within the component.

Both props and states are plain JavaScript objects. While props allow components to be dynamic and reusable, states enable them to be interactive.

Creative Explanation

Think of props like the settings on a coffee machine (a component). You set the type of coffee, amount of sugar, and size of the cup (props) before you start brewing. These settings are given to the machine and don't change during the brewing process.

State, on the other hand, is like the water level in the coffee machine's tank. It's internal and changes over time (e.g., it decreases as you make more coffee). The machine (component) checks and adjusts the water level (state) internally to function correctly.

Practical Explanation with Code

Here's an example demonstrating both props and states:

import React, { useState } from 'react';

function Greeting(props) {
  const [name, setName] = useState(props.initialName);

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <input type="text" value={name} onChange={e => setName(e.target.value)} />
    </div>
  );
}

export default Greeting;

In this component, initialName is a prop used to set the initial state ofname. Thename state is then used to display and update the greeting message interactively.

Real-World Example

Consider an online shopping platform. Each product page is a component. The product details (like name, price, and image) are passed as props from a parent component (e.g., product list) to the product page component. The quantity selected by the user for purchase is managed as a state within the product page component. As the user changes the quantity, the state updates, and the component reflects these changes (like updating the total price) without affecting the props (the product details).

Did you find this article valuable?

Support Akash Thoriya by becoming a sponsor. Any amount is appreciated!