#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Class Based Components

Class Based vs Functional Component

React lets you write components in two ways: as an ES6 class that extends React.Component, or as a plain JavaScript function. Both return JSX and both can receive props. The difference lies in how they hold state, respond to lifecycle events and share logic. Knowing both matters because many existing codebases still contain class components, even though new code is usually written as functions with hooks.

The same counter, written twice

// Class component
import React, { Component } from 'react';

class CounterClass extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.increment = this.increment.bind(this);
  }

  componentDidMount() {
    document.title = `Count: ${this.state.count}`;
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.count !== this.state.count) {
      document.title = `Count: ${this.state.count}`;
    }
  }

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

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

// Function component
import { useState, useEffect } from 'react';

function CounterFunction({ label }) {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return <button onClick={() => setCount((c) => c + 1)}>{label}: {count}</button>;
}

Both render the same button. The class version needs a constructor, this everywhere, a bound method and two lifecycle methods that repeat the same line. The function version does it with one state hook and one effect.

Side-by-side comparison

AspectClass componentFunction component
StateOne this.state object, updated with this.setState, which merges keys.Any number of useState calls; each setter replaces its own value.
LifecyclecomponentDidMount, componentDidUpdate, componentWillUnmount.useEffect with a dependency array and an optional cleanup function.
Propsthis.props.nameFunction parameter, often destructured.
Sharing logicHigher-order components or render props.Custom hooks.
Error boundariesSupported via componentDidCatch and getDerivedStateFromError.Not available as a function; a class or a library wrapper is needed.

Thinking in lifecycles versus thinking in effects

Classes ask "what should happen when the component mounts, updates or unmounts?" so related code gets split across methods. A subscription is started in componentDidMount and stopped in componentWillUnmount, sometimes far apart in the file. Effects ask "what should stay in sync with these values?" and keep setup and cleanup together in one place. That grouping is a main reason the React team recommends function components for new work.

The classic class-component bug

The best-known pitfall in classes is losing this. If you pass onClick={this.increment} without binding the method in the constructor, or without defining it as an arrow function class field, this is undefined when the click happens and this.setState throws. A second trap is reading this.state right after calling setState; updates may be batched, so use the updater form setState(prev => ...) when the new value depends on the old one.

Function components have their own trap, stale closures, where an effect or handler uses an old value because a dependency was left out of the array. The lint rule for hooks catches most of these.

When you will still meet classes

  • Older projects and tutorials written before hooks existed.
  • Error boundaries, which still require a class.
  • Libraries whose examples extend Component.

There is no need to rewrite working class components just to modernise them. Both styles can live in the same app and pass props to each other freely.

Choosing between them

For new components, use functions with hooks: less code, logic grouped by purpose, and easy reuse through custom hooks. Learn to read class components confidently, bind their methods correctly and map their lifecycle methods to effects, because you will maintain them in real projects.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course