16 min read

React Native Tips and Tricks (Part 1/2)

React Native

A beginners guide to the best practices to follow when coding

Rootcode - React Native

The goal of this article is to present you with React Native programming tips that you and your team may use. Some of these suggestions are exclusive to React Native, while others are more generally associated with mobile application development or any development. So, let’s get this party started right away!

01. Expo or No Expo?

Are you planning to create cross-platform apps with React Native? When you start building apps with React Native, you’ll encounter the decision of whether or not to use Expo.

Let’s see the advantages and disadvantages of using Expo.

Expo

Advantages

  • Easy to use
  • Immediate results
  • Everything is covered by Expo
  • Nice documentation from Getting started to all API Docs
  • Live reload while in development
  • Library linking (react-native link) is not necessary
  • Test directly on the device both for iOS and Android (through the Expo container app)
  • Develop from Windows/macOS or whatever (you only need nodejs and an internet connection)

Disadvantages

  • The build is done by Expo, in their cloud
  • Native modules not supported
  • Expo apps don’t support background code execution (source docs.expo.io)
  • Javascript source is hosted in their cloud
  • The app size can be large (around 30MB)

So the summary of this is, make sure not to use the Expo for complex or long-term projects. It is the best tool for newcomers to React Native technology and people who are doing simple projects.

As an example, if you are preferred to do a project using Expo, first thing is to make sure every requirement that you are supposed to use within your project is available in Expo libraries. Otherwise, there is no point in using it.

02. Folder structuring

The folder structure in any project is very important for every developer. Because a good folder structure will give a clear and clean idea about your project and organizing within components and everything inside it.

As an example;

Rootcode - React Native

As a developer, I preferred to use the Atomic design system for my projects as a folder structuring method. 

So,
What is this Atomic Design?

Brad Frost created the term “atomic design” to describe a way of constructing design systems. About 5 years ago, he introduced the concept of atomic design. It is the methodology that can help you create modular designs faster. Using chemistry as a metaphor, this methodology examines the links between the many pieces of the system and how they interact.

There are five distinct levels in atomic design:

  1. Atoms
  2. Molecules
  3. Organisms
  4. Templates
  5. Pages

Why is this important?

  1. Make the process of designing modular designs go faster.

Now, instead of walking through every single page to alter the layout on every single instance of our card design, we can just go to our atoms and molecules and make changes there, and everything will be updated.

2. Improved communication and execution

Furthermore, the atomic design is the means through which we can work together on the same project. Any modifications we make will be reflected in everyone else’s work if we update our libraries with the most recent variants of all these reusable components.

Atomic design methodology
Atomic design methodology 
  • Atoms are UI elements that can’t be broken down any further and serve as the elemental building blocks of an interface.
  • Molecules are collections of atoms that form relatively simple UI components.
  • Organisms are relatively complex components that form discrete sections of an interface.
  • Templates place components within a layout and demonstrate the design’s underlying content structure.
Rootcode - React Native
  • Pages apply real content to templates and articulate variations to demonstrate the final UI and test the resilience of the design system.
Rootcode - React Native

03. Use ESLint & Prettier

Prettier takes care of your code formatting.
ESLint takes care of your code styles.

  • First, make sure you have Prettier and ESLint installed. You can install them on a per-project basis or globally.
  • Second, install the Prettier and ESLint extension/plugin for your editor/IDE.
  • Third, install two more packages that are in charge of combining Prettier and ESLint (Only single quotes are used by Prettier, and the line length is set to the specified amount of characters. ESLint, on the other hand, requires a lot of configuration from you because it isn’t as opinionated as Prettier. Therefore, instead of adding all the ESLint rules ourselves, we can use the most popular code style guide for JavaScript published by Airbnb. You can install it with all its dependencies)

npx install-peerdeps — dev eslint-config-airbnb

  • Last but not least, set the Prettier rules in your ESLint configuration.

04. On using external libraries

If there is a library out there that satisfies your needs and isn’t abandoned, it’s better to use it instead of reinventing the wheel. You’ll save your precious development time for something else. However, you do need to do some research on the libraries you plan to use.

As a rule of thumb, if learning to use an external library is going to take more of your time than making everything yourself, you should stay away from it.

Sometimes you will want to change something in an external library. Do not edit it directly in the node_modules/ folder. That folder is supposed to be ignored by version control anyway, so if you change the code directly, your teammates will not see your changes. In addition, an npm update action will overwrite your modifications. The solution is to either fork the original repository and link your project to your own repository where you made the changes (and even make a PR to the original author if you want to help!), or if the library is very small (one file), you can copy/paste it as a component in your own project and then edit it locally.

When you are selecting a library, you have to ask the below questions yourself to find out the best library which can fulfill your requirement.

  1. Is it active and regularly maintained?
  2. Does it have a good rating?
  3. Is it well tested?
  4. Does it have a lot of issues?
  5. Does it support both iOS and Android?

06. Be Very Careful With Copy/Paste

You might want to copy a component, function, or some other piece of code and modify it. This is where a lot of unexpected errors happen because it can be very hard to notice a single property or value that you forgot to modify. So always be on your toes while doing any type of copy/paste.

07. Avoid using Find/Replace Functionality For Refactoring

It might seem like a faster solution if you need to quickly change a bunch of things on your project quickly, but there are way too many pitfalls you can (and trust me, you will) fall into. So just don’t even bother with it, and do things the old-fashioned way, or refactor using the refactoring tools provided by your IDE.

08. Use The Most Comfortable Ide As Your Editor

React Native is the latest cross-platform mobile development trend, allowing us to create high-quality, native, and powerful mobile apps with JavaScript. It’s been less than a year since Facebook Inc. introduced the open-source React Native project, and there’s been a lot of progress in terms of development, support, plugins, tools, and integrations.

There are so many code editors for development that it’s often tough for me to pick the best one for a given programming language. I did some exploring when working with React Native and discovered some great IDE/editors for mobile app development. I’ve included information about the editors, plugins, and packages that are special to React Native.

09. DRY (Don’t Repeat Yourself) everywhere

If I had to name one programming principle that is a basis for everything else in software development, it would be the Don’t Repeat Yourself principle.

Don’t Repeat Yourself: To write your code in a non-repetitive manner. Extracting and expressing shared code between components as a module that can be imported and utilized in other components.

When you need to update the functionality of a code that is being used in several places. All we have to do now is alter that common code, and the changes will be reflected in all components that require it.

10. Extract reusable logic into custom hooks

According to the React docs,

Hooks allow us to reuse stateful logic without changing our component hierarchy.

They’re a superior alternative to the strategies that were previously employed in conjunction with class components. Higher-Order Components or render props may be familiar to you if you’ve been coding for a long.

It’s a good idea to develop a custom hook if you need to reuse stateful logic that has already been utilized in another functional component. You just invoke the hook as a function inside your components to encapsulate the logic.

Let’s look at an example where we need to change our UI based on screen size and want to retain track of the current window size when manually resizing the browser window.

const ScreenDimensions = () => {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });
  
  useEffect(() => {
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    window.addEventListener('resize', handleResize);
    handleResize();
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return (
  	<>
    	<p>Current screen width: {windowSize.width}</p>
        <p>Current screen height: {windowSize.height}</p>
    </>
  )
}

As you can see, the answer is simple, and there’s nothing wrong with stating it this way.

Now comes the challenging part. Consider how we might apply the same logic to another component, rendering a distinct UI (one for smartphones and one for desktops) depending on the current screen size.

Of course, we could simply copy the logic and paste it in. However, as you may know from the DRY principle, this is not a good practice.

Let’s have a look at our customized hook:

const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });
  
  useEffect(() => {
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    window.addEventListener('resize', handleResize);
    handleResize();
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return windowSize;
}

Now let’s call it inside our Screen Dimensions component:

const ScreenDimensions = () => {
  const windowSize = useWindowSize()
  
  return (
  	<>
    	<p>Current screen width: {windowSize.width}</p>
        <p>Current screen height: {windowSize.height}</p>
    </>
  )
}

This allows us to use any component to call the custom hook and preserve the return value (which is the current window size) in a variable that we can use inside the component.

Wrapping up

React Native is famous and widely used to create interactive UIs. React-Native comes with everything you need and you most likely wouldn’t need more. Initially, when you start a new project you will notice how easy it is starting from the setting up process: it’s very fast and only takes you one command line to run in the terminal and you will be ready to go. As a frequent user of React Native, the above-mentioned practice tips have helped me become an efficient programmer in terms of front-end development and I hope following them will help you to avoid a lot of problems in a long run. 
For more tips and tricks, await part 2!