Flat Preloader Icon

Props and State

In React, “props” and “state” are essential concepts used for managing data and rendering components dynamically.

Props

  • Definition: Short for “properties”, props are read-only attributes used to pass data from a parent component to a child component.
  • Characteristics:
  1. Immutable: Once passed, props cannot be changed by the child component.
  2. Pure Data: Props are used purely to pass data and cannot maintain any internal state.
  3. Unidirectional Flow: Data flows from parent to child, maintaining a one-way data binding.

Usage:

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

function ParentComponent() {
  const data = "Hello from Parent!";
  return <ChildComponent message={data} />;
}

export default ParentComponent;

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

function ChildComponent(props) {
  return <div>{props.message}</div>;
}

export default ChildComponent;

				
			

State

  • Definition: State is an object that holds dynamic data and determines how the component renders and behaves.
  • Characteristics:
  1. Mutable: State can be changed over time, usually in response to user actions or other events.
  2. Local: State is managed within the component, but can be passed down to child components via props.
  3. Triggers Re-renders: Updating the state causes the component to re-render, reflecting the new state.

Usage (using React Hooks):

				
					import React, { useState } from 'react';

function StatefulComponent() {
  // Declare a state variable named 'count' with an initial value of 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default StatefulComponent;