← Back to Chapters

React Native Class Components

? React Native Class Components

? Quick Overview

Class Components are one of the traditional ways to create components in React Native. They use ES6 classes and provide lifecycle methods such as componentDidMount. Although modern apps prefer functional components, class components are still important for understanding legacy code and core React concepts.

? Key Concepts

  • Uses ES6 class syntax
  • Extends React.Component
  • Uses this.state for state management
  • Lifecycle methods control component behavior

? Syntax / Theory

A class component must extend React.Component and must include a render() method which returns JSX.

? View Code Example
// Basic class component structure
import React from "react";
import { Text, View } from "react-native";

class HelloWorld extends React.Component {
  render() {
    return (
      <View>
        <Text>Hello from Class Component</Text>
      </View>
    );
  }
}

export default HelloWorld;

? Code Example – State & Lifecycle

? View Code Example
// Class component with state and lifecycle method
import React from "react";
import { Text, View, Button } from "react-native";

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

  componentDidMount() {
    console.log("Component Mounted");
  }

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

  render() {
    return (
      <View>
        <Text>Count: {this.state.count}</Text>
        <Button title="Increase" onPress={this.increment} />
      </View>
    );
  }
}

export default Counter;

? Live Output / Explanation

The screen initially displays Count: 0. Each button press updates the state using setState(), causing the component to re-render with the new value.

? Interactive Example

Interact with the simulator below to understand how the state updates in real-time.

? Phone Simulator
Count: 0
> System Ready...

? Use Cases

  • Maintaining older React Native projects
  • Understanding lifecycle methods deeply
  • Learning React fundamentals

? Tips & Best Practices

  • Always bind methods or use arrow functions
  • Avoid direct state mutation
  • Move to functional components for new projects

? Try It Yourself

  • Create a class component with a timer
  • Use componentDidMount to start the timer
  • Clear it using componentWillUnmount