A Short Note – Functional vs Class Components in React Native

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Functional vs Class Components in React Native).

In this note series, we will understand about the difference between Functional and Class Components in React Native.

So Let’s begin.

In React Native, there are two main types of components that make up an application: functional components and class components. These are structured the same as they would be in a regular React app for the web.


Class Components vs Functional Components


1. Syntax

Class components are JavaScript ES2015 classes that extend a base class from React called Component and create a render function that returns a React element. This requires more code as well.

The Class Component in React Native

class App extends Component {
    render () {
        return (
            <Text>Hello World!</Text>
        )
    }
}
export default App;

A Functional Component looks like a plain JavaScript function and are sometimes called stateless components.

The Functional Component in React Native

const App = () =>{
	return (
	  <Text>Hello World!</Text>
	)
}
export default App;


2. State

In Class components, there is a way to store and manage state built in to React Native. This gives the class App access to the React life cycle methods like render as well as state/props functionality from the parent. While managing the state in classes, we use setState and this.state to set and get the state, respectively.

State in Class Component

mport React from 'react';
import {Text, View} from 'react-native';

class App extends React.Component {
	constructor(props){
		super(props);
		this.state = { value:0};
		setInterval(() =>{
			this.setState({ value: this.state.value + 1});
		}, 1000);
	}

	render() {
		return (
			<View>
				<Text>{'State Value =>' + this.state.value}</Text>
			</View>
		);

	}
}

export default App;

But in the functional component, we have useState hook after the update of React 16.8. They don’t manage their own state by React Native.

State in Functional Component

import React, { useState } from 'react';
import {Text, View} from 'react-native';

const App = () => {
		let [value, setValue] = useState(0);
		
		setInterval(() =>{
			setValue(value + 1);
		}, 1000);
	
		return (
			<View>
				<Text>{'State Value =>' + value}</Text>
			</View>
		);
};

export default App;


3. Lifecycle Methods/Hooks

Another most important difference in Class and Functional Component is the life cycle methods, or we can say Lifecycle Hooks. We all know how important is the Lifecycle methods while developing any React Native application. Life cycle methods give us the power to control the data and application flow on different activities. We are very much familiar with the class component Lifecycle methods but in case of Functional Components we have to manage all this with the help of useEffect hook.

Example of Lifecycle Methods for Class Component

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    }
  }

  componentDidMount() {
    const interval = setTimeout(() => {
      this.setState({ count: this.state.count + 1 });
    }, 1000);
    return () => {
      clearInterval(this.interval);
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <Text> Count incremented {this.state.count} times</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Example of useEffect Hook for Functional Component

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount
  useEffect(() => {
    const interval = this.setTimeout(() => {
      setCount(count + 1);
    }, 1000);
    return () => {
      clearInterval(this.interval);
    }
  }, []);

  return (
    <View style={styles.container}>
      <Text> Count incremented {count} times</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


Conclusion

In this note series, we understood about the difference between Functional and Class Components in React Native. We conclude that :

  • Class components are used as container components to handle state management and wrap child components.
  • Functional components are just used for display purposes – these components call functions from parent components to handle user interactions or state updates. 

Thanks for reading! I hope you enjoyed and learned about Functional Vs Class Components Concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

ReactJS – A Overview of class components and functional components with Hooks

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about class components and functional components differences and which one is best use for Hooks. A famous quote about learning is :

The beautiful thing about learning is that nobody can take it away from you.”

So Let’s begin.

The simplest way to define a component in React is to write a JavaScript function that returns a React element:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

The Welcome component accepts props which is an object that contains data and returns a React element. We can then import and render this component in another component.

The class component uses a programming methodology called Encapsulation which basically means that everything relevant to the class component will live within it. Life-cycle methods (constructorscomponentDidMount()render, and so on) give components a predictable structure.

Encapsulation is one of the fundamentals of OOP (Object-Oriented Programming). It refers to the bundling of data within the methods that operate on that data, and is used to hide the values or state of a structured data object inside a class — preventing unauthorized parties’ direct access to them.

With Hooks, the composition of a component changes from being a combination of life-cycle Hooks — to functionalities with some render at the end.

Function Component

The example below shows how custom Hooks can be used in a functional component (without showcasing what the body is). However, what it does or can do is not limited. It could be instantiating state variables, consuming contexts, subscribing the component to various side effects — or all of the above if you’re using a custom hook!

function {
  useHook{...};
  useHook{...};
  useHook{...};
  return (
    ...
  );
}

Class Component

class component requires you to extend from React.Component and create a render function which returns a React element. This requires more code but will also give you some benefits.

class {
  constructor(props) {...}
  componentDidMount() {...}
  componentWillUnmount() {...}
  render() {...}
}

So, Which one is best for Hooks ?

The Answer is :

There are some benefits you get by using functional components in React:

  1. It will get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState() in your component.
  2. Functional components are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks.
  3. You end up with less code.
  4. The React team mentioned that there may be a performance boost for functional components in future React versions.

This leads to the first best practice when using React Hooks.

That’s all about in this article.

Conclusion

In this article, We understood the Class component and functional component differences and benefits in Hooks with Which one is best for Hooks.

Thanks for reading ! I hope you enjoyed and learned about React class components and functional components differences and which one is best use for Hooks. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version