Junior
What is the concept of 'state' and 'props' in React development?
sobes.tech AI
Answer from AI
State is the internal state of a component, a set of data that can change during the component's lifecycle. Changing the state causes the component to re-render.
Props are external parameters passed to the component from outside, from the parent component. Props are immutable within the component that receives them. They are used for configuration and passing data from parent to child.
Main differences:
| Characteristic | State | Props |
|---|---|---|
| Source | Internal to the component | Passed from outside |
| Mutability | Can change | Cannot be changed inside |
| Purpose | Managing internal view | Passing data and configuration |
Example of using state:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
Example of using props:
import React from 'react';
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>; // Using props
}
function App() {
return <Greeting name="World" />; // Passing props
}