React Native -Best Practices
Improve performance and code hygiene by following the below pointers.
Putting imports in an order
a. React import
b. Library imports (Alphabetical order)
c. Absolute imports from the project (Alphabetical order)
d. Relative imports (Alphabetical order)
e. Import * as
f. Import ‘./<some file>.<some extension>
Each kind should be separated by an empty line. This makes your imports clean and easy to understand for all the components, 3rd-party libraries, etc.
Use a consistent naming convention for your components, variables, and functions. This will make your code more readable and easier to maintain.
Example:
import React from 'react';
import { View, Text } from 'react-native';
const MyComponent = () => {
const myVariable = 'Hello, World!';
const myFunction = () => {
console.log('This is my function.');
};
return (
<View>
<Text>{myVariable}</Text>
</View>
);
};export default MyComponent;
Use descriptive names for your components and variables. This will make your code more self-explanatory and easier to understand.
Example:
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
const HomePage = () => {
const greetingText = 'Welcome to My App!';
return (
<View style={styles.container}>
<Text style={styles.text}>{greetingText}</Text>
</View>
);
};const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 24,
fontWeight: 'bold',
color: 'blue',
},
});export default HomePage;
Use functional components whenever possible. Functional components are simpler and easier to read than class components.
Example:
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
const Counter = () => {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
};
return (
<View>
<Text>{count}</Text>
<Button title="Increment" onPress={handleIncrement} />
</View>
);
};export default Counter;
Use props to pass data and functions between components. This will make your code more modular and easier to reuse.
Example:
import React from 'react';
import { View, Text, Button } from 'react-native';
const MyComponent = ({ message, onButtonClick }) => {
return (
<View>
<Text>{message}</Text>
<Button title="Click Me" onPress={onButtonClick} />
</View>
);
};export default MyComponent;
Use destructuring to extract data from props and states. This will make your code more concise and easier to read.
Example:
import React, { useState } from 'react';
import { View, Text } from 'react-native';
const MyComponent = ({ title, subtitle }) => {
const [count, setCount] = useState(0);
return (
<View>
<Text>{title}</Text>
<Text>{subtitle}</Text>
<Text>{count}</Text>
</View>
);
};export default MyComponent;
Perform the API Calls in componentDidMount()
In order to always have the correct flow of data and render the components, you must put all your API calls within the componentDidMount() life cycle method.
Using componentDidMount() makes it clear that the data won’t be loaded until after the initial render. This will assist you in setting up the initial state properly, so you don’t end up with an undefined state that results in errors.
If using react native hooks, then write your API calls within the useEffect
useEffect(()=>{
//Your Api Call
},[])
Avoid Inline Stylings
Using inline stylings is much harder to maintain if a change is to be made there will be hundreds of places in the code you will have to search and change unless all styles are clearly defined with unique class names in a CSS stylesheet. For any property you want to change, you would have to simply modify the corresponding class name properties in the stylesheet, all the divs that use the class name will be affected.
A well-defined stylesheet is extremely helpful while building complex React Native apps. Use React Native Stylesheet object to add styles specific to a certain component.
Don’t Repeat Yourself — DRY principle
One of the basic principles of software development is Don’t Repeat Yourself. We must not write the same piece of code twice. Whenever you write the same piece of code twice, you must try to refactor it into something reusable, even if not completely.
You can create your own reusable components. For example, if your app contains multiple input fields, you can create a reusable <TextInput> component and use it across any screen within your app. Not only input fields, if your app contains multiple buttons, but you can also create a reusable <Button> component and use it anywhere within your app. Likewise, you can create any number of reusable components based on the app architecture.
Make Sure Your App is Responsive
You must always make sure that the app you are building is responsive, meaning it is consistent across different devices and platforms.
Don’t put logs in the release build
Having many console.log statements can slow your app down, especially if you are using logging libraries such as redux-logger. Be sure to disable all logs (manually or with a script) when doing a release build.
Use a linter to make your code easier to review.
Follow strict linting rules. This in turn helps you write clean, consistent code.
It’s important to follow best practices and write clean, maintainable code to ensure the longevity and success of our project.