🧠 React Core Concepts & Syntax
Estimated reading: 4 minutes 29 views

πŸ›οΈ React Class Components Explained – Syntax, State, Lifecycle (2025)


🧲 Introduction – Why Learn React Class Components?

Although functional components with Hooks are now the modern React standard, class components still exist in many production codebases. Knowing how class components work helps in maintaining legacy projects, understanding React’s evolution, and improving your overall React expertise.

🎯 In this guide, you’ll learn:

  • What class components are in React
  • How to use state and props
  • Lifecycle methods like componentDidMount
  • Event handling and common use cases

πŸ—οΈ What is a Class Component?

A class component is an ES6 class that extends React.Component and must contain a render() method that returns JSX.

βœ… Basic Syntax:

import React from 'react';

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

πŸ“Œ It can accept props, manage internal state, and use lifecycle methods.


🧠 Using State in Class Components

To add internal data (state), you define a constructor() and initialize this.state.

Example:

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

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return <button onClick={this.increment}>Count: {this.state.count}</button>;
  }
}

πŸ” setState() is used to update the component state and trigger a re-render.


πŸŽ›οΈ Props in Class Components

Props are accessible via this.props inside methods or JSX.

class Greeting extends React.Component {
  render() {
    return <h2>Hello, {this.props.username}!</h2>;
  }
}

You can pass them like:

<Greeting username="Alice" />

πŸ” Lifecycle Methods in Class Components

Lifecycle methods are special functions React calls at specific stages of a component’s life.

πŸ”„ Common Lifecycle Methods:

MethodPurpose
constructor()Initialize state or bind methods
render()Return JSX to render UI
componentDidMount()Runs once after the component mounts
componentDidUpdate()Runs after updates to state/props
componentWillUnmount()Cleanup before unmounting (e.g., clear timers)

Example:

class Timer extends React.Component {
  componentDidMount() {
    console.log('Component mounted');
  }

  componentWillUnmount() {
    console.log('Component unmounted');
  }

  render() {
    return <h2>Running...</h2>;
  }
}

🎯 Event Handling in Class Components

React class components require binding or arrow functions to handle events properly.

Binding in constructor:

constructor(props) {
  super(props);
  this.handleClick = this.handleClick.bind(this);
}

Or use arrow functions:

handleClick = () => {
  alert("Button clicked!");
};

render() {
  return <button onClick={this.handleClick}>Click Me</button>;
}

πŸ› οΈ When to Use Class Components

βœ… Use class components when:

  • You’re working with legacy React projects
  • Using React libraries that haven’t migrated to hooks
  • You want to understand React’s historical lifecycle architecture

⚠️ Avoid for new projects unless compatibility is required.


πŸ“‹ Class vs Functional – Code Comparison

πŸ›οΈ Class Component:

class Hello extends React.Component {
  render() {
    return <h2>Hello, {this.props.name}</h2>;
  }
}

🎯 Functional Equivalent:

function Hello({ name }) {
  return <h2>Hello, {name}</h2>;
}

βœ”οΈ The functional version is cleaner, but the class version is still fully valid and useful in many codebases.


πŸ“Œ Summary – Recap & Next Steps

React class components remain relevant in legacy apps. While Hooks in functional components offer a simpler, more modern approach, understanding class components is essential for full React mastery.

πŸ” Key Takeaways:

  • Class components extend React.Component and use render()
  • State is managed using this.state and this.setState()
  • Lifecycle methods offer fine control over component behavior
  • Prefer functional components for new features, but maintain knowledge of class-based patterns

βš™οΈ Real-World Relevance:
Many enterprise and open-source apps still use class components. Knowing how to work with them ensures you can maintain and refactor large-scale legacy codebases.


❓ FAQ Section

❓ Are class components deprecated?
βœ… No. React still supports class components, but they are no longer the recommended approach for new development.


❓ Can I use hooks in class components?
❌ No. Hooks like useState and useEffect only work inside functional components.


❓ When should I use componentDidMount()?
βœ… Use it to fetch data, start timers, or subscribe to events when the component is first rendered.


❓ How do I update the state in a class component?
βœ… Use this.setState():

this.setState({ key: newValue });

❓ Can I convert a class component to functional?
βœ… Yes. You can rewrite class components using functional syntax and use Hooks to replace lifecycle methods and state.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ›οΈ React Class Components Explained

Or Copy Link

CONTENTS
Scroll to Top