• 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!
Gal Normal

Ready to learn about State and Props in React?

Geek Curious

Sure! What's State?

Gal Happy

State is the internal data of a component. It's like the component's private memory!

  • State
Gal Pleased

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
    };
  }
}
Geek Happy

I see! So we define state in the constructor of a class component.

Gal Happy

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);
}
Geek Happy

Got it! We use the useState hook in functional components to manage state!

Gal Happy

That's right! To update state, use the setState method in class components or the state updater function in functional components.

  • Props
Gal Pleased

Now let's talk about Props! Props are short for "properties" and are used to pass data from one component to another.

Geek Curious

How do we use props?

Gal Happy

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" />;
Geek Happy

Oh, so we pass data to components using props like HTML attributes and access it inside the component!

Gal Happy

Exactly! Props make it easy to share data between components!

  • Hilarious Example
Geek Curious

Can we have a hilarious example with State and Props?

Gal Pleased

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="😃" />;
Geek Happy

Haha, that's funny! We're using both State and Props to create a Mood Changer component!

Gal Happy

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! 🚀