Understanding React Concepts: State and Prop

Understanding React Concepts: State and Prop

Examples of React state and props

React, with its declarative and component-based approach, relies on key concepts like state and props to manage and pass data. This blog aims to explain the differences between state and props with examples.

State

State is the internal handling of data of a component. It provides the component's dynamic properties, which might change over time.

Features:

  1. Local to Component: State is specific to the component it belongs to.

  2. Mutable: It can be modified using setState.

  3. Component-owned: Controlled and managed by the component itself.

Props

Props (short for properties) are external inputs passed to a component. They allow the parent component to communicate with and customize its child components.

Features:

  1. Immutable: Props are read-only and cannot be modified by the child component.

  2. Received from Parent: Passed down from parent to child.

  3. Pure Functions: Components that rely only on props are pure and deterministic.

Examples of State and Props

State Example:

Consider a counter component that manages its count using state.

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

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

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

In this example, count is a piece of state managed by the Counter component.

Props Example:

Now, let's create a Greetings component that receives a name prop.

import React from 'react';

const Greetings = (props) => {
  return <p>Hello, {props.name}!</p>;
};

Here, name is a prop passed from the parent component when rendering Greetings:

import React from 'react';
import Greetings from './Greetings';

const App = () => {
  return <Greetings name="John" />;
};

Understanding the difference between state and props is important for React developers. State enables components to manage internal dynamic data, while props help in communication between parent and child components.

Thanks for reading!