React js

Working with state and props

Working with State and Props in React


What are Props?

  • Props (short for properties) are read-only inputs passed from a parent component to a child component.

  • They allow components to be dynamic and reusable by customizing their content or behavior.

  • Props are immutable inside the child component.


Example of Using Props

jsx
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

// Using the component with different props
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}

Here, name is a prop passed into Greeting to personalize the greeting.


What is State?

  • State is internal data managed within a component.

  • State can change over time, usually in response to user actions or events.

  • When state changes, React re-renders the component to update the UI.

  • Only class components or functional components with hooks manage state.


Using State in Functional Components with Hooks

React’s useState hook lets you add state to functional components.

jsx
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // Declare state variable "count" with initial value 0

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}

  • count is the current state.

  • setCount is a function to update the state.

  • Calling setCount triggers a re-render with the new value.


Using State in Class Components

jsx
import React, { Component } from 'react';

class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 }; // Initialize state
}

increment = () => {
this.setState({ count: this.state.count + 1 }); // Update state
};

render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.increment}>Click me</button>
</div>
);
}
}

  • this.state holds the internal state.

  • Use this.setState() to update it.


Props vs State Summary

Feature Props State
Passed from Parent component Managed within the component
Mutable inside component? No (read-only) Yes (can change over time)
Purpose To customize component To manage internal dynamic data
Who controls? Parent component The component itself

Passing State as Props

You can pass state values as props to child components for controlled data flow.

jsx
function DisplayCount(props) {
return <p>Count: {props.count}</p>;
}

function App() {
const [count, setCount] = React.useState(0);

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


Summary

  • Props: inputs passed down, read-only, for customizing components.

  • State: internal, mutable data managed by components for dynamic behavior.

  • React re-renders components when state changes to update the UI.

Leave a Reply

Your email address will not be published. Required fields are marked *