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.
class syntaxReact.Componentthis.state for state managementA class component must extend React.Component and must include a render() method which returns JSX.
// 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;
// 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;
The screen initially displays Count: 0. Each button press updates the state using setState(), causing the component to re-render with the new value.
Interact with the simulator below to understand how the state updates in real-time.
componentDidMount to start the timercomponentWillUnmount