React Native – 7 Effective Patterns To Improve Development Experience

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about the React Native 7 effective simple patterns which helps to improve our react native experience during development mode. We will discuss about react native 7 effective simple patterns one by one.

  • Keep most of components stupid
  • Rely on callbacks
  • Keep navigation stack away from views
  • Keep callbacks chained together
  • Keep reducers simple and declarative
  • Keep business logic out of Reducers
  • Keep platform-specific components to a minimum

A famous quote about Learning is :

Tell me and I forget, teach me and I may remember, involve me and I learn.

So Let’s begin.


Pattern 1 : Keep most of components stupid

  • This is true for any React application. Our views and components should rely on props and callbacks while Container (smart) components should rely on state.
  • We recommend using Redux, but in some applications we can get away using plain old setState. MobX is a great alternative too.


Pattern 2 : Rely on callbacks

  • When we learn how to code iOS apps in Swift, we taught to use the delegate pattern to decouple a view from its behavior. In React Native, the same effect can be achieved via callbacks.
  • Callbacks are simply Arrow Functions which can be passed to a component. The component has the responsibility to execute them, but doesn’t need to know what it’s actually doing.
  • Most component should not have any behavior. Expose simple callbacks, they are like the public API of our components. We should know when they’ll be executed by reading their names. If we are developing an e-commerce app, for example, names like onSelectProduct or onProductAddedToShoppingCart are very declarative.
  • When deciding whether to expose a callback or not, every time a component has some kind of user interaction, ask ourself this:
    Is this interaction only important for this particular component, or can it trigger changes in another part of the application? ” If the latter is our answer, then we should expose a callback.


Pattern 3 : Keep navigation stack away from views

  • For this particular application, we were able to migrate from React Native’s default Navigator, to NavigationExperimental, to React Navigation. Those changes involved a few lines of code.
  • The idea is simple: Screens and Views are not the same. Our views should not have any knowledge of the Navigation Stack while Screens (or Routes, depending on what name we prefer) must know how to navigate and how to communicate with the Navigation Bar / TabBar. With this approach, our screens will simply wrap the actual Views with navigation-aware things, For example:
const FavoritesView = ({ favorites, onSelectFavorite }) =>    

const FavoritesScreen = ({ navigation }) =>
   navigation.push('FAVORITE', {{ favorite: favorite }})}/>

const NavigationStack = StackNavigator({
  FAVORITES: FavoritesScreen,
  FAVORITE: FavoriteScreen
})
  • As we can see, FavoritesView simply exposes an ‘onSelectFavorite’ callback and doesn’t care about what it actually does. FavoritesScreen uses that callback to tell the navigator to navigate to another screen. Therefore, this gives us the flexibility to replace the way our navigation stack works and provides a nice separation.


Pattern 4 : Keep callbacks chained together

  • A very common pattern is to inject behavior into callbacks within Higher order Components (that’s what Redux’s mapStateToProps actually does), but many people forget that a public callback may be used in another part of the app (an outer component, for example).
  • Every time one of our views exposes a callback which may be used in another part of our application (such as, mapStateToProps), first invoke the actual callback passed on props. This enables us to, for example, Navigate to a screen and also fetch some information to feed the next view.
const mapDispatchToProps = (dispatch, props) => ({
   onSelectFavorite: (favorite) => {
     props.onSelectFavorite(favorite);
     dispatch(fetchFavoriteInfo(favorite.id));
   }
})

const mapStateToProps = (state) => ({
   favorites: state.favorites
})

export default connect(mapStateToProps, mapDispatchToProps)(FavoritesView)
  • Following the previous example, if FavoritesScreen told FavoritesView to navigate to the FavoriteScreen when selecting a Favorite, Redux would honor that, but also invoke some Redux actions.
  • As we may see, every realm knows how to handle its stuff: Screens know how to navigate, Connected Views know how to handle redux actions and Views are dumb, stateless and rely on their props.


Pattern 5 : Keep reducers simple and declarative

  • Any developer should be able to view your reducer’s code and understand what it’s doing. In most cases, having one function per action type can increase readability. For example:
const clear = (favoriteId) => state => ...
const fetching = (favoriteId) => state => ...
const finishFetching = (favoriteId, favorite) => state => ...

export default (state = {}, action) => {
    switch (action.type) {
        case 'CLEAR_FAVORITE':
            return clear(action.favoriteId)(state);
        case 'FETCHING_FAVORITE':
            return fetching(action.favoriteId)(state);
        case 'FINISH_FETCHING_FAVORITE':
            return finishFetching(action.favoriteId, action.favorite)(state);
        default:
            return state;
    }
}
  • Composing reducer functions with many one-line functions can give us greater flexibility and code reuse.


Pattern 6 : Keep business logic out of Reducers

  • Redux store is not part of business model, it’s a View Model. Treat it like such. Reducer should only impact the store with changes, and we need to be highly confident of them. The less knowledge Reducers have of own business rules, the simpler they’ll become.
  • It’s not the best approach, but a better one to put business logic in action creators, specially if we use a middleware like Thunk. Sagas and Epics are great too.


Pattern 7 : Keep platform-specific components to a minimum

  • Every platform has its own Design/UX language and in many cases we have to write different versions of a component. Remember that React Native’s aim is learn once, write anywhere, but first try not to rush into writing platform-specific components.
  • In many cases, simple Style-changes and conditional operators are enough. we’ve created a simple helper function called platformSpecific which allows me to set styles according to a platform.It’s a really simple function, but incredibly useful. For example :
const platformSpecific = ({ios, android}) => (Platform.OS == ‘ios’) ? ios : android

That’s all about in this article.


Conclusion

In this article, We understood the React Native 7 effective simple patterns with the below summary :

  • Keep most of the components simple and dumb
  • Expose callback
  • Keep navigation stack separate from views
  • Keep callbacks chained together
  • Reducer code should be simple and declarative form
  • Application business logic should be separated from Reducer
  • Platform specific components should be used minimum. Use common components code for different platforms if possible.

Thanks for reading ! I hope you enjoyed and learned about the React Native 7 effective simple patterns. 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 !!???

React Native – An Overview Of React Native Foundation

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about the React Native Foundation. We will discuss  about react native core concepts through examples. 

A famous quote about learning is :

I am still learning.

So Let’s begin.


What Is React Native ?

React Native is like React, but it uses native components instead of web components as building blocks. So to understand the basic structure of a React Native app, we need to understand some of the basic React concepts, like JSX, components, state, and props.

If we already know React, we still need to learn some React-Native-specific stuff, like the native components.

Let’s do this thing.

Hello World

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

function HelloWorldApp() {
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Text>
        Hello, world!
      </Text>
    </View>
  );
}
export default HelloWorldApp;

What’s going on here?

  1. First of all, we need to import React to be able to use JSX, which will then be transformed to the native components of each platform.
  2. On line 2, we import the Text and View components from react-native.

Then we find the HelloWorldApp function, which is a functional component and behaves in the same way as in React for the web. This function returns a View component with some styles and aText as its child.

The Text component allows us to render a text, while the View component renders a container. This container has several styles applied, let’s analyze what each one is doing.

The first style that we find is flex: 1, the flex prop will define how our items are going to “fill” over the available space along your main axis. Since we only have one container, it will take all the available space of the parent component. In this case, it is the only component, so it will take all the available screen space.

The following style is justifyContent: “center”. This align children of a container in the center of the container’s main axis and finally we have alignItems: “center”, which align children of a container in the center of the container’s cross axis.React Native ships with ES2015 support, so you can use this stuff without worrying about compatibility. importfromclass, and extends in the example above are all ES2015 features.

The other unusual thing in this code example is Hello world!

This is JSX – a syntax for embedding XML within JavaScript. In React, this is reversed. JSX lets you write your markup language inside code. It looks like HTML on the web, except instead of web things like <div> or <span> you use React components. In this case, <text> is a Core Component that displays some text and View is like the <div> or <span>.


React Native Fundamentals

React Native runs on React, a popular open source library for building user interfaces with JavaScript. To make the most of React Native, it helps to understand React itself.

We’re going to cover the core concepts behind React native :

  • Components
  • JSX
  • props
  • state


Components

So HelloWorldApp example code is defining HelloWorldApp, a new Component. When we’re building a React Native app, we’ll be making new components a lot. Anything we see on the screen is some sort of component.


JSX

React and React Native use JSX, a syntax that lets we write elements inside JavaScript like so: <Text>Hello, I am your cat!</Text>.

Because JSX is JavaScript, we can use variables inside it. Here we are declaring a name for the cat, name, and embedding it with curly braces inside <Text>.

import React from 'react';
import { Text } from 'react-native';

const Cat = () => {
  const name = "Maru";
  return (
    <Text>Hello, I am {name}!</Text>
  );
}

export default Cat;

Because JSX is included in the React library, it won’t work if we don’t have import React from 'react' at the top of our file!


Props

Most components can be customized when they are created, with different parameters. These creation parameters are called props.

Our own components can also use props. This lets us make a single component that is used in many different places in our app, with slightly different properties in each place. Refer to props.{NAME} in our functional components or this.props.{NAME} in our class components. Here’s an example:

import React from 'react'; import { Text, View, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ center: { alignItems: 'center' } }) function Greeting(props) { return ( <View style={styles.center}> <Text>Hello {props.name}!</Text> </View> ); } function LotsOfGreetings() { return ( <View style={[styles.center, {top: 50}]}> <Greeting name='Rexxar' /> <Greeting name='Jaina' /> <Greeting name='Valeera' /> </View> ); } export default LotsOfGreetings;

Using name as a prop lets us customize the Greeting component, so we can reuse that component for each of our greetings. This example also uses the Greeting component in JSX. The power to do this is what makes React so cool.

The other new thing going on here is the View component. A View is useful as a container for other components, to help control style and layout.

With props and the basic TextImage, and View components, we can build a wide variety of static screens. To learn how to make our app change over time, we need to learn about State.


State

Unlike props that are read-only and should not be modified, the state allows React components to change their output over time in response to user actions, network responses and anything else. Here’s an example:

import React, { Component } from 'react' import { StyleSheet, TouchableOpacity, Text, View, } from 'react-native' class App extends Component { state = { count: 0 } onPress = () => { this.setState({ count: this.state.count + 1 }) } render() { return ( <View style={styles.container}> <TouchableOpacity style={styles.button} onPress={this.onPress} > <Text>Click me</Text> </TouchableOpacity> <View style={styles.countContainer}> <Text> You clicked { this.state.count } times </Text> </View> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, button: { alignItems: 'center', backgroundColor: '#DDDDDD', padding: 10, marginBottom: 10 } }) export default App;

In this example,

  1. First of all, we need to import React to be able to use JSX, which will then be transformed to the native components of each platform.
  2. On line 2, we import the StyleSheet , TouchableOpacity , Text and View components from react-native
  3. In next line , we defines a new class  App which extends from React Component .This block of code defines the components that represent the user interface.
  4. After that, we initialize  our app state variable count  to 0 inside App class using  state  variable.
  5. After that we create  onPress()  method where count  is incremented by 1 and count   value is set in  setState()  method.
  6. After that Inside render()  method that returns a react element , includes:
    • A  return()  that returns the result of layout and UI components.
    • A container View  that supports the layout accessibility controls. It is a fundamental component for building the UI.
    • A  TouchableOpacity  wrapper is used to reduce the opacity of button. Here, onPress method is called using onPress props.
    • A React component Text  for displaying text.
    • A property style  used for styling the components using  StyleSheet class.
    • styles   is used to design individual components.
  7. After that, the  StyleSheet  class creates the style object that controls the layout and appearance of components. It is similar to Cascading Style Sheets (CSS) used on the Web.

That’s all about in this article.


Conclusion

In this article, We have discussed about React Native Foundations Concepts like Components,Props and State through example explanations. So we conclude that

  • Components : Everything is component in React Native.The way in which you create a new component.
  • Props : Most components can be customized when they are created, with different parameters. These creation parameters are called props.
  • State : State allows React components to change their output over time in response to user actions, network responses and anything else.

Thanks for reading ! I hope you enjoyed and learned about the React Native Foundation. 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 !!???

React Native – How React Native Works Internally?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about the React Native Internal architecture. This article will discuss React Native internal work flow.

A famous quote about learning is :

” Try to learn something about everything and everything about something. “

So, Let’s Start.

Overview

” React Native is a framework which allows developers to build native apps using javascript.”

So What about Cordova Platform and why would anyone want to use React Native?

The Primary difference between React Native and Cordova based app is that

  • Cordova based apps run inside a Web View. 
  • React Native apps renders using Native View.

React Native Application have direct access to all the native APIs and views offered by the underlying mobile OS. React Native Applications have the same feel and performance as that of a native application.

We can assume that React native might be compiling JS code into respective native code directly. But this would be really hard to achieve since Java and Objective C are strongly typed languages while Javascript is not!

React Native does something much more clever.Essentially React Native uses a set of React components, where each component represents the corresponding native views and components.

For example, a native TextInput will have a corresponding React Native component which can be directly imported into the JS code and used like any other React component. Hence, the developer will be writing the code just like for any other React Web app but the output will be a native application.

To understand this, let us take a look at the architecture and Threading model and how React Native works internally.


Architecture

React Native uses similar architecture for iOS and Android platform. There are three parts to React Native Platform :


1. Native Code/Modules

Most of the native code in case of iOS is written in Objective C or Swift, while in the case of Android it is written in Java. But for writing our React Native app, we would hardly ever need to write native code for iOS or Android.


2. JavaScript VM

  • The JS Virtual Machine that runs all our JavaScript code. On iOS/Android simulators and devices React Native uses JavaScriptCore, which is the JavaScript engine that powers Safari. JavaScriptCore is an open source JavaScript engine originally built for WebKit. 
  • In case of iOS, React Native uses the JavaScriptCore provided by the iOS platform. It was first introduced in iOS 7 along with OS X Mavericks.
  • In case of Android, React Native bundles the JavaScriptCore along with the application. This increases the app size. Hence the Hello World application of RN would take around 3 to 4 megabytes for Android.
  • In case of Chrome debugging mode, the JavaScript code runs within Chrome itself (instead of the JavaScriptCore on the device) and communicates with native code via WebSocket. Here, it will use the V8 engine. This allows us to see a lot of information on the Chrome debugging tools like network requests, console logs, etc.

3. React Native Bridge

React Native bridge is a C++/Java bridge which is responsible for communication between the native and Javascript thread. A custom protocol is used for message passing.


Threading Models

When a React Native application is launched, it spawns up the following threading queues:


1. Main Thread (Native Queue)

  • Main thread gets spawned when application launches. It loads the app and starts the JS thread to execute the JavaScript code.
  • The Native thread also listens to the UI events like ‘press’, ‘touch’ etc. These events are then passed to the JS thread via RN Bridge.
  • Once the Javascript loads, the JS thread sends the information on what needs to be rendered onto the screen.This information is used by a shadow node thread to compute the layout.
  • The Shadow thread is basically like mathematical engine which finally decides on how to compute the view positions.
  • These instructions are then passed back to the main thread to render the view.


2. JavaScript Thread (JS Queue)

  • The Javascript Queue is the thread queue where main bundled JS thread runs. 
  • The JS thread runs all the business logic, i.e., the code we write in React Native. 


3. Custom Native Modules

  • Apart from the threads spawned by React Native, we can also spawn threads on the custom native modules to build to speed up the performance of the application.
  • For Example – Animations are handled in React Native by a separate native thread to offload the work from the JS thread.

That’s all about in this article.


Conclusion

In this article, We understood about React Native Internal Work Flow. We conclude that React Native work flow based on the threading models and process involved between different threads. We can separate React Native into three Parts :

  • React Native-Native Side
  • React Native -JS Side
  • React Native – Bridge

This is also called “3 Parts of React Native”.

Thanks for reading ! I hope you enjoyed and learned about Internal architecture,Threading Models and Process involved in React Native . 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