Introduction to State
In React, state refers to the data that changes over time and affects the rendering of a component. State is used to store data that is specific to a component and is used to render the component.Using State
To use state in a functional component, you can use the `useState` hook:
import React, { useState } from 'react';function Counter() {
const [count, setCount] = useState(0);return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}In this example, the `useState` hook is used to create a state variable `count` and an `setCount` function to update the state.
Introduction to Props
Props are short for "properties" and are used to pass data from a parent component to a child component. Props are read-only and cannot be changed by the child component.Using Props
To use props in a component, you can pass them as an argument to the component function:
import React from 'react';function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}function App() {
return <Greeting name="John" />;
}In this example, the `Greeting` component receives a `name` prop from the `App` component.
Props vs State
Props State Purpose Pass data from parent to child Store data that changes over time Mutability Read-only Mutable Scope Component tree Single component
Example Code
Here's an example of a simple React app that uses state and props:
import React, { useState } from 'react';function Counter(props) {
const [count, setCount] = useState(0);return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Name: {props.name}</p>
</div>
);
}function App() {
return <Counter name="John" />;
}
Here's a practice exercise:
Create a simple React app that displays a list of items. Each item should have a name and a price. Use state to store the list of items and props to pass the item data to a child component.
Hint: Use the `useState` hook to create a state variable for the list of items. Use a child component to render each item in the list. Pass the item data as props to the child component.