logo
React Native Practical - Interview Questions and Answers
What are functional vs. class components in React Native?

In React Native (and React in general), components are the building blocks of your user interface. Historically, there were two main ways to define components: class components and functional components. However, with the introduction of React Hooks, functional components have become the dominant and recommended approach. Here's a breakdown:

Class Components:

  • Definition:
    • Class components are JavaScript classes that extend React.Component.
    • They must have a render() method that returns the JSX (JavaScript XML) that defines the component's UI.
  • Features:
    • They can maintain their own internal state using this.state.
    • They have access to lifecycle methods (e.g., componentDidMount, componentDidUpdate, componentWillUnmount), which allow you to perform actions at specific points in the component's lifecycle.
  • Example :
  • import React, { Component } from 'react';
    import { Text } from 'react-native';
    
    class MyClassComponent extends Component {
      render() {
        return <Text>Hello from a class component!</Text>;
      }
    }
    
    export default MyClassComponent;

     

Functional Components:

  • Definition:
    • Functional components are JavaScript functions that accept props as arguments and return JSX.
    • They are simpler and more concise than class components.
  • Features:
    • With the introduction of React Hooks, functional components can now manage state using useState and perform side effects using useEffect, effectively replicating the capabilities of class components.
    • They tend to be easier to read and test.
  • Example :
  • import React from 'react';
    import { Text } from 'react-native';
    
    const MyFunctionalComponent = () => {
      return <Text>Hello from a functional component!</Text>;
    };
    
    export default MyFunctionalComponent;

Key Differences and the Impact of Hooks :

  • State Management:
    • Before Hooks, only class components could manage state.
    • Now, functional components can manage state using the useState hook.
  • Lifecycle Methods:
    • Class components have lifecycle methods.
    • Functional components can achieve similar effects using the useEffect hook.
  • Simplicity:
    • Functional components are generally simpler and more concise.
  • Hooks:
    • React Hooks have significantly changed how we write React components. They allow functional components to "hook into" React state and lifecycle features. This has made functional components the preferred choice for most React developers.