Sobes.tech
Junior

What is the difference between props and state in React?

sobes.tech AI

Answer from AI

Props and state are two key mechanisms for managing data in React components.

Props:

  • Are passed from a parent component to a child.
  • Are immutable within the child component.
  • Allow components to interact with each other.
  • Define the appearance or behavior of a component based on input data.

State:

  • Belongs to a specific component and is managed by it.
  • Is mutable within the component.
  • Represents data that can change over time and affect the rendering of the component.
  • Changing the state triggers a re-render of the component and its children.

The main differences can be summarized in a table:

Characteristic Props State
Source Parent component The component itself
Mutability Immutable Mutable
Management Passed from outside Managed inside the component
Purpose Displaying external data, configuration Managing internal component state
Change triggers Re-rendering when changed in parent Re-rendering when changed in the current component

Example of using props:

// ParentComponent.jsx
import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const message = "Hello from parent!";
  return (
    <div>
      <ChildComponent text={message} /> {/* Passing prop "text" */}
    </div>
  );
}

export default ParentComponent;
// ChildComponent.jsx
import React from 'react';

function ChildComponent(props) {
  return (
    <p>{props.text}</p> {/* Using prop "text" */}
  );
}

export default ChildComponent;

Example of using state:

// Counter.jsx
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0); // Initializing state "count"

  const increment = () => {
    setCount(count + 1); // Changing state
  };

  return (
    <div>
      <p>Counter: {count}</p>
      <button onClick={increment}>Increase</button>
    </div>
  );
}

export default Counter;