• Introduction Now let’s learn about class components in React. Class components are another way to create components, and they can manage state and use lifecycle methods. Our characters, Geek and Gal, will help us understand class components with their fun interactions!
Gal Normal

Alright, time to learn about class components in React!

Geek Curious

Oh, cool! How are they different from functional components?

Gal Happy

Class components are based on JavaScript classes, and they can manage state and use lifecycle methods. Before React Hooks, they were the only way to do this!

  • Class Components
Gal Pleased

A class component is a JavaScript class that extends React.Component . To create one, you'll need a render() method that returns JSX. Here's an example of a class component:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}
Geek Happy

Got it! So a class component is a JavaScript class that extends React.Component , and it has a render() method that returns JSX!

Gal Happy

That's right! And to use a class component, you write it as a custom HTML tag, just like functional components:

<Welcome name="Charlie" />
Geek Curious

What about managing state and using lifecycle methods in class components?

Gal Pleased

Great question! Class components have a this.state object to manage state, and you can update it using this.setState() . As for lifecycle methods, there are several, like componentDidMount() , componentDidUpdate() , and componentWillUnmount() !

Gal Normal

Here's a hilarious class component that displays a joke and allows you to update it:

class JokeBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      joke: 'Why did the chicken cross the road? To get to the other side! 😂',
    };
  }

  updateJoke() {
    this.setState({
      joke: 'Why couldn’t the bicycle stand up by itself? It was two-tired! 😂',
    });
  }

  render() {
    return (
      <div>
        <p>{this.state.joke}</p>
        <button onClick={() => this.updateJoke()}>Update Joke</button>
      </div>
    );
  }
}
Geek Happy

Haha, that's funny! Class components seem really powerful!

Gal Happy

They are! However, since React Hooks were introduced, many developers now prefer functional components. But it's still important to understand class components as you may encounter them in older projects or certain use cases. 😊

  • Conclusion Class components in React are based on JavaScript classes and can manage state and use lifecycle methods. They’re a bit more complex than functional components, but understanding them is essential for working with older projects or specific situations. Keep on learning, and you’ll become a React pro in no time! 🌟