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 !!???

A Short Note – 7 Quick Valuable Commands To Improve React Native Development

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (7 Quick Valuable Commands To Improve React Native Development).

In this note series, we will learn about seven quick valuable commands which is commonly used and helps to improve React Native Development to start developing iOS and Android apps.


So, Let’s begin.


1. Starting a new project

There are different ways, we can bootstrap a react native application. You can use Expo or create-react-native-app (which in turns uses Expo-Cli) to start our new project, but with this method, we are in more control of what happened in our project and can communicate, tweak and write our own modules with native libraries for iOS and Android mobile platform.

react-native init [PROJECT-NAME]
cd [PROJECT-NAME]


2. Run app in Android Emulator

This command is self explanatory and as it says it will start the Android emulator and install the app you just created. You need to be in the root of the project to run this command.

react-native run-android


3. Run app in iOS Emulator

This command do exactly the same as react-native run-android but instead of the Android emulator, it opens the iPhone simulator.

react-native run-ios


4. Link dependencies to native projects

Some libraries have dependencies that need to be linked in the native code generated for React Native. If something doesn’t work after you installed a new library, maybe is because you skip this step.

react-native link [LIBRARY-NAME]


5. Clear bundle

If something don’t run as expected, maybe you need to clear and create a new bundle with this command.

watchman watch-del-all


6. Support decorators

JSX doesn’t support decorators by default so you need to install the Babel plugin to make it work.

npm install babel-plugin-transform-decorators-legacy --save
npm install babel-plugin-transform-class-properties --save


7. Export APK to run in device

With the following commands you will have and unsigned apk so you can install and share with your colleagues for testing purposes. Just remember that this apk is not ready to upload to the App Store or production. You will find your fresh apk in android/app/build/outputs/apk/app-debug.apk.


Bundle debug build

react-native bundle --dev false --platform android --entry-file index.android.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug


Create debug build

cd android
./gradlew assembleDebug


Conclusion

In this note series, we understood about seven quick valuable commands which is commonly used in React Native Development.

Thanks for reading! I hope you enjoyed and learned about React Native Commands List. 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, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – Unit Vs Integration Vs End To End Testing

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Unit Vs Integration Vs End To End Testing).

In this note series, we will understand about the difference between unit testing, integration testing and End to end testing in React Testing Framework.

So Let’s begin.


Unit Testing

Unit Testing is an isolated part of your app, usually done in combination with shallow rendering.

Example: A component renders with the default props.


Integration Testing

Integration Testing if different parts work or integrate with each other. Usually done with mounting or rendering a component.

Example: Test if a child component can update context state in a parent.


End To End Testing

It stands for end to end (e to e testing) . Usually a multi step test combining multiple unit and integration tests into one big test. Usually very little is mocked or stubbed. Tests are done in a simulated browser, there may or may not be a UI while the test is running.

Example: Testing an entire authentication flow.


Conclusion

In this note series, We understood about the difference between unit testing, integration testing and End to end testing in React Testing Framework. 

Thanks for reading ! I hope you enjoyed and learned about Unit Testing Vs Integration Testing Vs End to end Testing Concepts in React Testing Framework. 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 as below links :

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 !!???

A Short Note – What Is Difference Between Shallow And Mount In React Testing ?

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series.

In this note series, we will discuss about difference between Shallow and Mount in React Testing.

So Let’s begin.

Mount

Mount actually executes the html, css and js code like a browser would, but does so in a simulated way. It is “headless” for example, meaning it doesn’t render or paint anything to a UI, but acts as a simulated web browser and executes the code in the background.

Not spending time painting anything to the UI makes your tests much faster. However mount tests are still much slower than shallow tests.

This is why you unmount or cleanup  the component after each test, because it’s almost a live app and one test will affect another test.

Mount/render is typically used for integration testing.

Shallow

Shallow is used for unit testing. Shallow rendering only renders the single component we are testing. It does not render child components. This allows us to test our component in isolation.

When writing unit tests for React, shallow rendering can be helpful. Shallow rendering lets you render a component “one level deep” and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.

Conclusion

In this note series, We understood about the difference between Shallow and Mount in React Testing. So we conclude that

  • Shallow() tests components in isolation from the child components they render while mount() goes deeper and tests a component’s children.
  • Mount(<Component />) for Full DOM rendering is ideal for use cases where you have components that may interact with DOM apis, or may require the full lifecycle in order to fully test the component (ie, componentDidMount etc.) while shallow(<Component />) for Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren’t indirectly asserting on behavior of child components.
  • Mount/render is typically used for integration testing while Shallow is used for unit testing.

Thanks for reading ! I hope you enjoyed and learned about Shallow and Mount Concepts in React Testing. 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