What Are Props in React?

Key Points About Props

  1. Props are passed as attributes to components.
  2. They are immutable inside the child component.
  3. Props help in one-way data flow.

Simple Example

  1. App.jsx
    import React from "react";
    import Parent from "./Parent";
    
    function App() {
      return (
        <>
          <Parent />
        </>
      );
    }
    
    export default App;
    
  2. Parent.jsx
    import React from "react";
    import Child from "./Child";
    
    function Parent() {
      return (
        <>
          <h2>This is Parent component </h2>
          <Child name="Manav Pandya" />
        </>
      );
    }
    
    export default Parent;
    
  3. Child.jsx
    import React from "react";
    
    function Child(props) {
      return (
        <>
          <h3>This is child component </h3>
          <p>Hello,Good Morning {props.name}</p>
        </>
      );
    }
    
    export default Child;
    

In this example

  1. App Component (App.js): Renders the Parent component.
  2. Parent Component (Parent.js): Renders a heading and the Child component and passes the prop name "Manav Pandya" to the Child component.
  3. Child Component (Child.js): Receives the name prop and displays Hello, Good Morning Manav Pandya.

What is Props Drilling in React?

Example of Props Drilling

function App() {
  const user = "Jay";
  return <Parent user={user} />;
}

function Parent({ user }) {
  return <Child user={user} />;
}

function Child({ user }) {
  return <GrandChild user={user} />;
}

function GrandChild({ user }) {
  return <h2>Hello, {user}</h2>;
}

In this example

Problems with Props Drilling

Solution

Conclusion

Props are the backbone of component communication in React, enabling seamless data sharing. They promote reusability and dynamic UI without altering the original data. Mastering props means writing cleaner, smarter, and more efficient React components.