Logo
Core Concepts
Core ConceptsComponents

Components

Understanding functional and class components in React Native.

What are Components?

Components are the building blocks of any React Native application. They encapsulate the logic, structure, and style of your UI. In React Native, there are two main types of components: Functional Components and Class Components.

Functional Components

Overview

Functional components are simpler and easier to test and debug. They are just JavaScript functions that return JSX. They don't have a state or lifecycle methods.

Example

Here's a simple example of a functional component that displays a greeting:

import React from 'react';
import { Text, View } from 'react-native';
 
const Greeting = ({ name }) => {
  return (
    <View>
      <Text>Hello, {name}!</Text>
    </View>
  );
};
 
export default Greeting;

Class Components

Overview

Class components are more feature-rich and allow you to use state and lifecycle methods. They are defined using ES6 classes.

Example

Here's an example of a class component that displays a counter:

import React, { Component } from 'react';
import { Text, View, Button } from 'react-native';
 
class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
 
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };
 
  render() {
    return (
      <View>
        <Text>Count: {this.state.count}</Text>
        <Button title="Increment" onPress={this.increment} />
      </View>
    );
  }
}
 
export default Counter;

When to Use Which?

  • Functional Components: Use these for simpler components that don't require state management or lifecycle methods.

  • Class Components: Use these for more complex components that require state management and lifecycle methods.

Book a conversation with us for personalize training today!

Was this helpful?
Logo