Skip to main content

Command Palette

Search for a command to run...

4) Props in React

Updated
  1. Concept of Props
    In React, props (properties) are a way to pass data from one component to another, typically from a parent component to a child component. They make components reusable, dynamic, and configurable.
    What are Props?
    i) Props are read-only JavaScript objects.
    ii) They allow you to pass data, functions, or even UI elements to child components.
    iii) Props help components behave differently based on the values passed to them.

    const Parent = () => {
      return <Child name="Rahul" age={25} />;
    }
    
    const Child = (props) => {
      return (
        <div>
          <p>Name: {props.name}</p>
          <p>Age: {props.age}</p>
        </div>
      );
    }
    
  2. Characteristics of props
    i) Parent Component → Child Component

    const Parent = () => {
      return <Child name="Rahul" age={25} />;
    }
    
    const Child = (props) => {
      return (
        <div>
          <p>Name: {props.name}</p>
          <p>Age: {props.age}</p>
        </div>
      );
    }
    

    ii) Props Are Read-Only
    You cannot modify props inside a child component. If you need to modify data, use state.

    props.name = "New Name"; // ❌ Not allowed
    

    iii) Using Destructuring with Props

    const Child = ({ name, age }) => {
      return <p>{name} is {age} years old.</p>;
    }
    

    iv) Passing Functions as Props
    Props can also carry functions — useful for handling events.

    const Parent = () => {
      const greet = () => alert("Hello!");
      return <Child onGreet={greet} />;
    }
    
    const Child = ({ onGreet }) => {
      return <button onClick={onGreet}>Click Me</button>;
    }
    
  3. Difference between Props and States
    i) Definition and Purpose
    a) Props (Properties) -
    Props are used to pass data from a parent component to a child component.
    They are read-only and meant to configure or customize a child component.
    Props are used to make components reusable and dynamic.
    b) States -
    State is a built-in object that holds data or information about the component.
    It is managed within the component (typically in class components or using the useState hook in functional components).
    State is mutable and can be changed over time, usually in response to user actions or events.

    ii) Mutability
    a) Props -
    Immutable. Once passed to a child component, they cannot be modified by that component.
    Controlled by the parent component.
    b) States -
    Mutable. It can be updated using methods like setState in class components or the useState hook in functional components.
    Managed and updated within the component.

    iii) Usage Context
    a) Props -
    Used for passing data and event handlers down the component tree from parent to child.
    Ideal for communication between components.
    b) States -
    Used for managing data that changes over time within a component.
    Ideal for maintaining local component data.

    iv) LifeCycle
    a) Props -
    Received from parent components and remain constant as long as the parent does not change them.
    Lifespan is tied to the parent component's render cycle.
    b) States -
    Initialized within the component and can change over the component's lifecycle.
    Lifespan is tied to the component itself and persists as long as the component exists.

  4. Key Props
    The key prop in React is a special attribute that you should include when creating lists of elements. It is used by React to identify which items have changed, are added, or are removed. This helps React efficiently update the user interface when the state of the application changes.
    When rendering a list of elements in React, each element should have a unique key prop. The value of key should be unique among siblings but does not need to be globally unique.

    import React from 'react';
    
    function ItemList({ items }) {
      return (
        <ul>
          {items.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      );
    }
    

    The key prop in React is crucial for identifying elements in a list and enabling efficient updates and rendering. By providing unique, stable keys, you help React optimize the reconciliation process, ensuring that your application runs smoothly and correctly handles dynamic content.

  5. propTypes
    In React, propTypes are a way to ensure that components receive the right type of props. By defining propTypes, you can catch bugs by validating the props passed to your components, ensuring they match the expected types. This is especially useful during development. React provides a built-in library called prop-types for this purpose.
    First, you'll need to install the prop-types package if you haven't already:

    npm install prop-types
    

    Here is an example of how to define and use propTypes in a React component:

    import React from 'react';
    import PropTypes from 'prop-types';
    
    const MyComponent = () => {
        return (
          <div>
            <h1>{this.props.title}</h1>
            <p>{this.props.description}</p>
            <p>Age: {this.props.age}</p>
          </div>
        );
    }
    
    MyComponent.propTypes = {
      title: PropTypes.string.isRequired,      // title is a required string
      description: PropTypes.string,            // description is an optional string
      age: PropTypes.number,                    // age is an optional number
    };
    
    export default MyComponent;
    

    Basic-Level Questions on Props
    i) What are props in React?
    ii) Why do we use props?
    iii) How do you pass props from a parent to a child component?
    iv) How does a child component access props?
    v) Are props in React read-only? Why?
    vi) Can props be modified inside a child component? Why or why not?
    vii) What is the difference between props and state?
    viii) Can props be used in functional and class components?
    ix) How do you pass a number, boolean, or object as props?
    x) What happens when props change? How does React respond?

  6. Intermediate-Level Questions on Props
    i) What are defaultProps? When do you use them?
    ii) What are propTypes? Why are they used?
    iii) Can you pass a function as a prop? Give an example.
    iv) How do you pass components or JSX as props (children prop)?
    v) What is props drilling? Why is it a problem?
    vi) How do you avoid props drilling? (Context API, Redux, etc.)
    vii) What is the difference between spread attributes and explicit props? Example: <Component {...props} />
    viii) How are props passed in class components?
    ix) What are controlled vs uncontrolled components in relation to props?
    x) Can you pass props to a component created using React.memo?

  7. Advanced-Level Questions on Props
    i) What are render props? How are they different from regular props?
    ii) What is the role of props in higher-order components (HOCs)?
    iii) How does props comparison help in optimizing React components? (Shallow comparison, React.memo, PureComponent)
    iv) What happens if a component receives new props but returns the same UI?
    v) How do you use destructuring to manage props effectively?
    vi) What is the difference between passing props and using context?
    vii) How do you deeply compare props to prevent unnecessary re-renders?
    viii) What are key props in lists? Why are they important?
    ix) How do you type-check props in TypeScript?
    x) What are the drawbacks of relying too much on props?