What are functional and class components in React Native?

Functional components in React Native are JavaScript functions that render a React element. They can accept a single argument which is an object containing component properties. They can also use state and lifecycle behavior with hooks.

Class Components in React Native are ES6 Classes that extend React.Component and render a React element. Although functionally similar to functional components, there are differences in how functional and class components are written. Let’s take a look at those differences below.

Syntax

Functional components, like normal JavaScript functions, can be defined using the arrow function syntax or the function keyword.

import React from 'react';
import { Text, View, } from 'react-native';
function FunctionalComponent(props) {
return (
<View>
<Text>React Native Functional Component</Text>
</View>
)
}

A class component is an ES6 class that extends React.Component. It requires a render() method which returns the UIUser Interface to be displayed.

import React from 'react';
import { Text, View, } from 'react-native';
class ClassComponent extends React.Component {
render() {
return (
<View>
<Text>React Native Class Component</Text>
</View>
)
}
}

Lifecycle and state

state in React Native is a JavaScript object that represents information about a component. Changing the value of a state property will cause a React Native component to be updated or re-rendered.

Class components initialize a state in its constructor, while functional components make use of the useState hook.

Nathan Sebastian goes in-depth about React hooks in this article.

Lifecycle in React Native is the series of processes a React Native component or application goes through from creation to complete rendering. It has three major stages:

  • Mounting
  • Updating
  • Unmounting

Class components move through these different stages in their life cycle using predefined methods, such as:

  • The constructor() function which is called before the component mounts.
  • The render() method which is a required method that should return null or a JSX element.
  • componentDidMount() runs after the component is rendered.
  • componentDidUpdate() runs immediately when the component is updated, but not on the first render.
  • componentDidUnmount() runs just before the component unmounts and is removed from the view.

Functional components make use of the useEffect() hook to access the life cycle behavior.

Free Resources