Fundamental Concepts of React Native

Learn via video courses
Topics Covered

Overview

Facebook created the React Native framework. With the help of this framework, you may produce genuine mobile applications that are equal to those created with Swift or Java. React native basics UI building pieces as of iOS and Android. These components are simply combined using JavaScript and React. A "bridge" is what React Native utilises to communicate. Even though JavaScript and Native threads are built in entirely separate languages, bidirectional communication is made possible thanks to the bridge feature.

Components in React

A component is one of React native basics. Or, to put it another way, every application you create with React will be built up of what are known as components. Using components makes creating user interfaces considerably simpler. You can see a user interface (UI) divided into numerous separate parts, or components, and work on them independently before merging them all into a parent component to create your final UI.

ReReact native basics components essentially return JSX code that specifies what should be displayed on the screen. There are primarily two categories of components in React:

Functional Components : Javascript functions are only functional components. Writing a javascript function allows us to build a functional React component. Data may or may not be passed as parameters to these functions.The example below illustrates a React functional component:

Class Components : Compared to the functional components, the class components are a little more complicated. While the class components can cooperate with one another, the functional components in your programme are unaware of the other components. Data can be passed across class components by using the pass method. To develop class-based components for React, we can use JavaScript ES6 classes. A React component that uses classes is demonstrated in the example below:

  • We use the first parameter when using ReactDOM.render().
  • Then React invokes the component Welcome, which produces the result "Hello World!"
  • After that, the returned element is accurately updated by ReactDOM to match the DOM and rendered to the element with the id root in the DOM.

State in React

The state is an instance of the React Component Class, which is a set of objects with observable characteristics that govern how the component behaves. In other words, a component's state is an object that contains data that could change throughout the component's existence. Consider the clock we built in React as an example. We used the render() method explicitly once every second, but React offers a better approach to accomplish the same goal by utilising State, which stores the value of time as a member of the component's state.

A state must remain as straightforward as feasible. It can be changed by calling the setState() method, and doing so causes UI modifications. The local state or data of a component is represented by a state. Only the component itself or the component itself can access or modify it. We must utilise the getInitialState() method to set an initial state before any interaction takes place.

One container component must be created to maintain the state for all of the components, for instance, if five components require data or information from the state.

The state of a component can change over time; each time it does, the component re-renders. The component's behaviour and rendering are determined by changes in state, which may occur in reaction to user input or system-generated events.

  • User action or network changes may cause a state to change.
  • React re-renders the component to the browser whenever an object's state changes.
  • The constructor initialises the state object.
  • The state object has the capacity to store numerous properties.The state object's value can be modified with setState().
  • The setState() function only slightly merges the former and new states.

Props in React

Props are an acronym for "properties." and is another React native basic. These components can only be read. It is an object that functions similarly to HTML attributes in that it stores the value of a tag's attributes. It provides a method for data to be sent between components. They are comparable to function arguments. The component receives props in the same manner as function parameters.

Since props are immutable, we are unable to change them from within the component. We can include props or attributes inside the components. These attributes may be used to render dynamic data in our render method and are accessible in the component as this.props.

The following example shows the use of a child component that renders the value passed by the parent:

JSX

All React components have a render function, as we have already seen in React native basics. A React component's HTML output is defined by the render function. A React extension called JSX (JavaScript Extension) enables the creation of JavaScript code that resembles HTML. To put it another way, JSX is an extension of ECMAScript utilised by React to allow HTML-like syntax to coexist with JavaScript/React code. Preprocessors (also known as transpilers, such as babel) use the syntax to convert HTML-like syntax into typical JavaScript objects that a JavaScript engine can interpret.

In the same file where you write JavaScript code, JSX enables you to write HTML/XML-like structures (such as DOM-style tree structures). A preprocessor will subsequently convert these expressions into JavaScript code. JSX tags have a tag name, attributes, and children much like XML/HTML tags do.

Here, we'll create JSX syntax in a JSX file and observe how the preprocessor (babel) turns it into JavaScript code.

JSX File <div>Hello World</div>

Corresponding Output React.createElement("div", null, "Hello World");

The line above generates a react element with three arguments, the first of which is the element's name, "div," the second of which is the attributes supplied in the div tag, and the third of which is the content you pass, Hello World.

Some advantages of using JSX are :

  • Because it does optimisation when converting the code to JavaScript, it is quicker than standard JavaScript.
  • React uses components that combine HTML and functionality rather than splitting technologies by putting them in distinct files. Components will be covered in a later section.
  • The majority of the mistakes may be identified during compilation because it is type-safe.
  • Making templates is made simpler. Attribute passing, commenting, nesting of elements and styling can also be done easily in JSX.

Virtual DOM

The virtual DOM, as its name suggests, is a much lighter version of the real DOM in the form of objects in other React native basics. Although it doesn't directly affect what is displayed on the user's browser, the virtual DOM can be saved in the browser's memory. React's declarative approach is distinct and is used by various other front-end frameworks, such as Vue.

Contrary to popular belief, the virtual DOM is not any quicker than or comparable to the real DOM. In actuality, the actions of the virtual DOM supplement and assist those of the actual DOM. In essence, the virtual DOM offers a method that enables the real DOM to compute only the necessary DOM operations while re-rendering the user interface.

For instance, the DOM will render the element and all of its children again when an element in the real DOM is modified. This method is slow and ineffective when it comes to creating intricate web applications with plenty of interactivity and state changes.

Instead, React uses the virtual DOM idea during rendering, which is consistent with its declarative methodology. As a result, we can declare the state we want the UI to be in, and React will then implement it.

React updates only the element that was changed on the actual DOM after comparing the new virtual DOM to a snapshot of the virtual DOM obtained immediately prior to the update. This is one technique used by the virtual DOM to enhance performance.

The virtual DOM abstracts manual DOM adjustments from the developer, enabling us to create more predictable and orderly code and allowing us to concentrate on building components.

virtually-dom

Lifting State Up

For React developers, lifting the state up is a useful idea because we frequently have a state that fits inside a single component but needs to be shared with its siblings.

By raising the state in React native basics, we transform the parent state into a single shared state that serves as the only "source of truth" and transmit the parent state's information to its offspring.

This idea is referred to as lifting the state. Maintaining data consistency in our react applications is quite helpful.

So when should the state-lifting procedure begin? Multiple components frequently need to reflect the same changing data. Additionally, it is advised to elevate the shared state up to the most recent common ancestor if the data between the "parent and children components" or "cousin components" is out of sync.

Let's say we have two components: a parent component called ParentComponent and a child component called ChildComponent. We want to lift up the state from the child component to the parent component.

Here's an example of how you can achieve that :

Explaination

In this example, the ParentComponent maintains the count state using the state hook. It also defines an increment count function that updates the count state when called.

The ParentComponent renders the ChildComponent and passes down the count state and the increment count function as props.

In the ChildComponent, when the button is pressed, it calls the incrementCount function received from the parent, which updates the state in the parent component. This way, the state is lifted up from the child component to the parent component.

Whenever the count state is updated in the parent component, both the parent and child components will be re-rendered, reflecting the updated state.

Fragment

In React, you must call a render method inside the component whenever you wish to display something on the screen. A single element or a collection of elements may be returned by this render method. Only one root node inside it will ever be rendered at a time via the rendering technique. However, the render function will require a 'div' tag and place the entire content or elements inside it if you wish to return several elements. The addition of this extra node to the DOM might occasionally cause your HTML output to be formatted incorrectly, and many developers dislike it.

React introduced Fragments in version 16.2 and later addressed this issue in React native basics. A list of children can be grouped using fragments without adding more nodes to the DOM.

Syntax :

The use of the fragments tag is most beneficial because:

  • In comparison to the div tag, it speeds up the execution of code.
  • Less memory is required.

Conditional Rendering

React Native and React are similar to each other in terms of conditional rendering. But keep in mind that only the Text component in React Native allows us to render strings. Therefore, if we attempt to insert a string inside a View, for instance, we will encounter an error.

Inline if with logical And operator

The double negation in the above code converts the error value into a boolean. It is crucial because if the left side of the condition is true, the logical "and" operator && will return the right side of the condition. If the left side is false, it will also return the condition's left side.

All operations will proceed as expected if the error variable is an object, null, or undefined. However, since we cannot render strings inside a View component, if we receive an empty string for the error (error = ''), then our component will break.

Inline if-else with ternary ? operator

Depending on our component structure and the return type, we can either return null or <></> (React Fragment) in this case.

if statement

Here the if statement has been used for conditional rendering.

FAQs

Q. Will my React app work on mobile? Will my React Native app work on the Web?

A. No. The majority of React code for the web depends on the functionality offered by web browsers, thus, it won't work on mobile devices, and vice versa. React native basics programme depends on features offered by a specific mobile platform. The good news is that some code can still be shared between mobile and web apps, and future code reuse will get better.

Q. Can apps be migrated to react native?

A. Yes, provided that your software does not rely on the device doing computationally intensive activities. React Native's capabilities are constantly growing, making it possible to create ever-more complicated apps.

Additionally, switching to React Native makes maintaining your project less expensive since there is only one codebase for both Android and iOS.

Q. Should I choose React Native or native (separate iOS and Android)?

A. For the majority of apps that largely rely on the user interface, React Native is fantastic because, most importantly, it allows us to share the business logic and makes it easy to get the UI to operate on both iOS and Android. In addition, React Native leverages Flexbox for layout, which is the same across iOS, Android, and the Web, allowing us to transfer our knowledge from that platform rather than having to learn yet another engine.

On the other hand, a native app is fantastic when we take advantage of all the features that a platform has to offer, including components like multithreading or video/audio processing. React Native can be less effective for applications with lots of native features because it primarily concentrates on the User Interface.

Conclusion

  • A component is one of React native basics building blocks.
  • React Native employs a Virtual DOM, a lightweight copy of the actual DOM.
  • React Native combines the benefits of native components with React's declarative UI paradigm.
  • A React extension called JSX (JavaScript Extension) enables the creation of JavaScript code that resembles HTML.
  • The virtual DOM, as its name suggests, is a much lighter version of the real DOM in the form of objects.
  • React Native supports hot reloading, which is another React native basic, which means you can see the changes you make in the code immediately reflected in the running app.
  • For React developers, lifting the state up is a useful idea because we frequently have a state that fits inside a single component but needs to be shared with its siblings.
  • React Native has a vibrant and active community, which means you can find plenty of resources, tutorials, and documentation to learn and solve problems effectively.