• Introduction Now that we have an overview of State and Props in React, let’s dive deeper into understanding State. Follow Geek and Gal as they explore the concept of State in React components.
Gal Normal

Ready to learn more about State in React?

Geek Curious

Absolutely! Let's do it!

Gal Happy

Great! State represents the internal data of a component. It can change over time and cause the component to re-render.

  • State in Class Components
Gal Pleased

In class components, you can define state in the constructor. Let's look at an example!

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
}
Geek Happy

I see, so we define the state in the constructor using this.state !

Gal Happy

Exactly! To update the state in a class component, you use the setState method. It's important to use setState instead of directly modifying this.state to ensure the component re-renders correctly.

incrementCount() {
  this.setState({ count: this.state.count + 1 });
}
  • State in Functional Components
Gal Pleased

Now let's see how we can manage state in functional components using hooks!

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
}
Geek Happy

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

Gal Happy

That's right! useState returns an array with two elements: the current state value and a function to update the state. You can use array destructuring to give them names like [count, setCount] .

function incrementCount() {
  setCount(count + 1);
}
Geek Happy

So we use the state updater function, like setCount , to update the state in functional components!

Gal Happy

Exactly! By updating the state, you can create dynamic and interactive components!

  • Hilarious Example
Geek Curious

How about a hilarious example with State?

Gal Pleased

Let's make a "Random Joke Generator" component that generates random jokes when a button is clicked!

import React, { useState } from 'react';

function RandomJokeGenerator() {
  const jokes = ['Joke 1', 'Joke 2', 'Joke 3', 'Joke 4'];
  const [joke, setJoke] = useState('');

  function generateJoke() {
    const randomIndex = Math.floor(Math.random() * jokes.length);
    setJoke(jokes[randomIndex]);
  }

  return (
    <div>
      <h1>Joke: {joke}</h1>
      <button onClick={generateJoke}>Generate Joke</button>
    </div>
  );
}
Geek Happy

Haha, that's a fun example! We're using State to create a Random Joke Generator component!

Gal Happy

I'm glad you like it! Keep practicing and create more exciting components with state!

  • Conclusion State is crucial for managing the internal data of React components.