- Introduction
In React, managing data and passing it between components is essential. In this chapter, we’ll learn about State and Props. Let’s see how our characters, Geek and Gal, explore these concepts!
Ready to learn about State and Props in React?
State is the internal data of a component. It's like the component's private memory!
You can use state in class components or functional components with hooks. Let's start with class components!
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
}
I see! So we define state in the constructor of a class component.
Exactly! Now let's see how we can use state in functional components with hooks!
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
}
Got it! We use the
useState
hook in functional components to manage state!
That's right! To update state, use the
setState
method in class components or the state updater function in functional components.
Now let's talk about Props! Props are short for "properties" and are used to pass data from one component to another.
You can pass props to a component just like HTML attributes! Here's an example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
const element = <Greeting name="Alice" />;
Oh, so we pass data to components using props like HTML attributes and access it inside the component!
Exactly! Props make it easy to share data between components!
Can we have a hilarious example with State and Props?
Sure! Let's make a "Mood Changer" component that changes its mood based on a prop!
import React, { useState } from 'react';
function MoodChanger(props) {
const [mood, setMood] = useState('😐');
function changeMood() {
setMood(props.newMood);
}
return (
<div>
<h1>Mood: {mood}</h1>
<button onClick={changeMood}>Change Mood</button>
</div>
);
}
const element = <MoodChanger newMood="😃" />;
Haha, that's funny! We're using both State and Props to create a Mood Changer component!
I'm glad you like it! Keep practicing and make your components even more interactive!
- Conclusion
State and Props are crucial for managing data in React. State is the internal data of a component, while Props are used to pass data between components. By understanding State and Props, you can build interactive and dynamic applications! 🚀