React Native Best Practices

Understanding Best Practices in Coding

In the coding world, ‘best practices’ refer to guidelines rather than strict rules. While it may seem optional initially, adhering to these suggestions is crucial as your codebase expands. While your code might function adequately without them initially, maintaining its health and readability becomes increasingly challenging as it grows.

 

Striver Tech

Alright, let’s get down to the main point. What are the React Native best practices? Well, they’re a bunch of guidelines that you can follow to create a maintainable codebase. In this article, we’ll go into more detail about these practices.

Are you delving into React Native development and striving for excellence in your mobile app projects? Striver brings you valuable insights and best practices to guide you on your journey to success.

Top 6 React Native Best Practices for 2024

Top 6 React Native Best Practices for 2024
1. Use TypeScript with Your React Native App

TypeScript is a statically typed programming language which means it requires explicitly defining the data types for variables, functions, and other elements. This not only leads to more reliable code but also helps developers catch bugs during the compilation process.

Consider the following to calculate the order price

function calculatePrice(order) {
return order.price + 200;
}

The current code works fine, but it doesn’t tell us much about what properties the order object contains, which could lead further to a crash if we try to access a property that doesn’t exist.

To prevent the crash and enhance readability, we can use TypeScript. TypeScript is a programming language that adds types to JavaScript. This means that we can specify the type of each property in the object, which will help us avoid errors.

interface Order {
price: number;
name: string;
taxPercentage: number;
}
function calculatePrice(order: Order) {
const { price, taxPercentage } = order;
const taxValue = price * taxPercentage;
return price + taxValue;
}

Here is the same function, but now you and your editor are aware of the object properties and their types in code, which makes it easier to extend the functionality.

2. Functional Components over the Class Components

In React Native, you will have two main components: Functional and Class components. But functional components are the way to go in React Native. They’re simpler, more concise, and faster than class components. This makes them easier to read, write, and test. Plus, they can improve your app’s performance.

If you’re not sure what components are, they’re functions that return React elements. So if you’re looking for a way to improve your React Native code, use functional components over class components. They’re the future of React Native development.

Class Component Example

import React, { Component } from 'react';
class ClassComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<View>
<Text style={styles.h1}>Class Component</Text>
<Text>Count: {this.state.count}</Text>
<Button title='Increment' onPress={this.incrementCount}/>
</View>
);
}
}
export default ClassComponent;

In this class component example, we’re using the Component class from React to create a component. The state is managed within the component’s constructor, and the render method defines the component’s UI.

Functional Component Example

import React, { useState } from 'react';
const FunctionalComponent = () => {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
return (
<View>
<Text style={styles.h1}>Functional Component</Text>
<Text>Count: {count}</Text>
<Button title='Increment' onPress={incrementCount}/>
</View>
);
};
export default FunctionalComponent;

In this functional component example, we’re using the useState hook from react to manage state. The component is defined as a simple JavaScript function that returns JSX to render the UI.

3. Import your dependencies in order

When you have a bunch of imports in one file, it could be a headache trying to find that one specific import you need if you have not organized your imports properly. Therefore it is essential to order imports invariably.

At the same time, you should also ensure that the dependencies have a proper sequence of imports. If the order is not correct, it can affect how components behave and lead to bugs that are hard to find.

Here’s an example of how you can organize your imports:

  1. External imports — react
  2. Internal imports, like relative paths — ../button
  3. In folder imports like ./styles.ts
  4. The imports may be sorted alphabetically in every group
  5. Every group must be divided by white space
import React from 'react';
import { TouchableOpacity, View } from 'react-native';
import { Button, Card } from '../components'
import { MainLayout } from '../layouts'
import { StyledCard } from './styles.ts'

You can use formatting tools like Eslint and Prettier to automate and enforce the correct import order to avoid such issues.

4. Use Path Alias to avoid long imports

Path aliases are a way to create shorter and more meaningful import paths in your code. This can be helpful when you have a deep or nested folder structure, and it can make your imports easier to read and understand.

For example, instead of writing a long import like this:

import { IconButton } from '../../components/buttons';
import { CircleButton } from 'components/buttons';
OR
import { CircleButton } from 'buttons';

Here’s how to use path aliases in both TypeScript and React Native to create shorter and more meaningful import paths in your code.

Here’s how to use path aliases in both TypeScript and React Native to create shorter and more meaningful import paths in your code.

  1. Path Alias in TypeScript
  • Create or update the tsconfig.json file in your project if it doesn’t exist already.
  • Set the baseUrl to . , which represents the root of the directory. This sets the starting point for all path aliases.
  • Add path aliases to the paths object. In this example, we have two path aliases defined:
// tsconfig.json
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
// Path alias config
"baseUrl": ".",
"paths": {
// This needs to be mirrored in babel.config.js
// Components is a directory with sub directories
"components/*": ["src/components/*"],
// We want to expose the exports of the buttons index file
"buttons": ["src/components/buttons/index"]
}
}
}

Now, TypeScript will be able to understand and parse the following imports:

import { CircleButton } from "components/buttons"
import { CircleButton } from "buttons"

2. React Native Path Alias

First, install the babel-plugin-module-resolver as a developer dependency

yarn add - dev babel-plugin-module-resolver
npm install babel-plugin-module-resolver - save-dev

Now we can update the babel.config.js file to use the **module-resolver**plugin and point to our directories.

**// babel.config.js**
module.exports = function (api) {
api.cache(true)
return {
presets: ["babel-preset-expo"],
plugins: [
[
"module-resolver",
{
alias: {
// This needs to be mirrored in tsconfig.json
components: "./src/components",
buttons: "./src/components/buttons",
},
},
],
],
}
}
5. Create Responsive Layout in Your React Native App

Responsive style properties in React refer to the use of functions to create an adaptive user interface or a layout that adjusts to various screen sizes and orientations. Developing a responsive React Native app can be done in multiple ways, and one of them is by using react-native-normalize. This handy library offers functions that help you create responsive layouts effortlessly.

6. Implement Crash Analytics Tools

Crash analytics tools are like your magic tools that keep an eye on your app 24/7. They do real-time monitoring to help you identify crashes and errors. These tools analyze the crash data and give you the lowdown on what’s causing the chaos.

So, if you’re in the development process, and suddenly, the app crashes out of the blue. With the implementation of crash analytics, you can easily find the root causes of these crashes.

There are a bunch of awesome crash analytics tools out there, like Sentry, Firebase, Crashlytics, and more. They’re like your trusty companions, helping you debug and rescue your app from potential crashes.

Dive Deeper with Striver

For an in-depth exploration of these React Native best practices and more, read our featured blog on Medium: React Native Best Practices by Striver.

At Striver, we are committed to empowering developers and businesses with the knowledge and expertise needed to excel in the dynamic world of React Native development. Stay tuned for more insightful content, and let’s shape the future of mobile app development together.

Ready to elevate your React Native projects? Connect with Striver, your trusted partner in innovative software solutions.

 

🚀💻 #ReactNative #MobileAppDevelopment #BestPractices #StriverTech #SoftwareDevelopment #TechInnovation