DEV Community

KIRAN RAJ
KIRAN RAJ

Posted on

React props

  1. What is Props?
  • Props stands for Properties in React.
  • Props are used to pass data from one component to another, usually from a parent component to a child component. -Props are read-only, meaning the child component cannot change them.

Simple definition:

Props allow components to communicate with each other by sending data.

2 Why Do We Need Props?

  • React follows a component-based architecture.
  • Each component should be independent and reusable.

Props help us to:

  • Share data between components
  • Reuse the same component with different values
  • Keep code clean and organized

❌ Without Props

You would have to hardcode values inside components.

✅ With Props

You can pass dynamic data easily.

3.How Props Work?

Props always work in one direction:

Parent ➡ Child

Step 1: Pass Props from Parent Component

function App() {
  return <Welcome name="Kiran" />;
}
Enter fullscreen mode Exit fullscreen mode

Here:

  • name is a prop
  • "Kiran" is the value

Step 2: Receive Props in Child Component

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Kiran
Enter fullscreen mode Exit fullscreen mode
  • Destructuring Props
function Welcome({ name }) {
  return <h1>Hello, {name}</h1>;
}

Enter fullscreen mode Exit fullscreen mode
  • This is the most commonly used method.

🔷 Props Are Read-Only

You cannot change props inside a child component.

❌ Wrong:

props.name = "Raj";
Enter fullscreen mode Exit fullscreen mode

✅ Correct:

  • Props should only be used, not modified
  • If data needs to change → use state

4.Where Are Props Used?

Props are used whenever data needs to be shared between components.

🔹 Common Use Cases
1️⃣ Passing Text

<Button label="Submit" />
Enter fullscreen mode Exit fullscreen mode

2️⃣ Passing Numbers

<Counter start={10} />
Enter fullscreen mode Exit fullscreen mode

3️⃣ Passing Functions

<Button onClick={handleClick} />

Enter fullscreen mode Exit fullscreen mode

4️⃣ Passing Objects

<User user={{ name: "Kiran", age: 24 }} />
Enter fullscreen mode Exit fullscreen mode

🔷 Props vs State (Quick Comparison):

Props State
Passed from parent Managed inside component
Read-only Can be changed
Used for communication Used for data changes
Immutable Mutable

🔷 Real-World Example :

Think of props like arguments in a function.

function greet(name) {
  return "Hello " + name;
}
Enter fullscreen mode Exit fullscreen mode

React version:

<Greet name="Kiran" />
Enter fullscreen mode Exit fullscreen mode

Same idea, different syntax.

🔷 Conclusion ✨

Props:

  • Help pass data between components
  • Make components reusable
  • Improve code structure and readability

Top comments (0)