Sitemap
Dilan

Dilan

props and state

2 min readApr 25, 2025

--

Props and state are fundamental concepts in React for managing data and component behavior.

Props (Properties)

  • Data Passing: Props are used to pass data from a parent component to a child component.
  • Unidirectional Flow: Data flows down the component tree, from parent to child.
  • Read-Only: Child components cannot modify props passed to them by their parent.
  • Similar to Function Arguments: They are like arguments passed to a function, providing input to the component.
  • Any Data Type: Props can be any JavaScript value, including strings, numbers, objects, arrays, and functions.
  • How to Pass: Props are passed as attributes when using a component, similar to HTML attributes
  1. code

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

Get Dilan’s stories in your inbox

Join Medium for free to get updates from this writer.

// Child Component
function Child Component(props) {
return <h1>{props.text}</h1>; // Accessing the 'text' prop
}

2. state

  • Internal Data: State is used to manage data within a component that can change over time.
  • Mutable: Unlike props, state can be updated by the component itself.
  • Local: State is private to the component and not accessible to other components directly.
  • Triggers Re-renders: When state is modified, React re-renders the component to reflect the changes in the UI.
  • How to Manage: In class components, state is an object accessed via this.state and updated using this.setState(). In functional components, the use State hook is used to manage state.
  • 2.code

// Functional Component with State
import React, { useState } from 'react';

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

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

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

--

--