Getting Started With React : Your First Step Towards Mastering React Native

React code in a web browser

Welcome to the world of React, a powerful JavaScript library that lays the foundation for mastering React Native. As an aspiring React Native developer, you might ask, “Why do I need to learn React for web?”

The answer lies in the underlying architecture of React Native, which is built upon the principles of React.

Let’s dive into it.

1. What is React?

1.1 What is React and Why it Matters for us React Native Developers

React is an open-source JavaScript library for building user interfaces, primarily for single-page applications. It was developed by Facebook and is now maintained by Facebook and a community of individual developers and companies. React allows developers to create reusable UI components that can update and render efficiently in response to changes in data, , helping them to write efficient code that is easier to debug and maintain. This makes React a great choice for building web applications where user interaction is key.

React Native, on the other hand, is a framework that allows you to build mobile applications using JavaScript and React. React Native translates your markup to real, native UI elements, leveraging existing means of rendering views on whatever platform you are working with.

In essence, most of the concepts and skills you learn in React directly translate to React Native. This is why understanding React is crucial for a smooth and effective development experience in React Native.

1.2 The Importance of Understanding React for React Native

React Native uses the same fundamental UI building blocks as regular iOS and Android apps. However, instead of building in Swift, Kotlin or Java, you’re putting these building blocks together using JavaScript and React. This means that the better your understanding of React, the more capable you’ll be when it comes to developing applications in React Native.


In the following sections, we will explore the basics of React, dive deeper into advanced topics, and finally, understand how it all connects back to React Native. Our goal is to equip you with the React knowledge you need to excel in your React Native journey.

So, let’s get started and dive into the exciting world of React!

2. The Basics of React

Let’s start with the fundamentals of React. By understanding these core concepts, you’ll be able to comprehend how React works under the hood, and you’ll be well-equipped to build your own React applications, setting the stage for your future in React Native development.

2.1 The Syntax : JSX

JSX is a syntax extension for JavaScript that is used to describe the structure of the user interface. It looks a lot like HTML, but it’s actually JavaScript. JSX is not required to write React applications, but it makes your React code more readable and writeable.

Given that it is a syntax extension of JavaScript, you cannot write some JSX inside a regular .js file. To do so, we use files with the .jsx extension.

Here’s an example of JSX in action:

const element = <h1>Hello, world!</h1>;

Here, we have created a React element (also called Virtual DOM) that represents an h1 HTML element with the text “Hello, world!”.

Later when we will tell React to actually render this element on the page, it will create a real <h1>Hello, world</h1> in the DOM of the page.

2.2 The Building Blocks: Understanding Components in React

In React, everything is a component. Components are the building blocks of any React application and you can think of them as JavaScript functions or classes that accept inputs, called “props”, and return a React element that describes how a section of the UI should appear.

They are reusable and can be nested inside other components, allowing you to build complex UIs from simple building blocks.

In React, we typically define components as plain JavaScript functions:

function Welcome() {
  return <h1>Hello, user!</h1>;
}

Here, Welcome is a React component that takes an object of properties, referred to as props, and returns a React element.

2.2 The Role of Props in React

Props (short for properties) are inputs to components. They are passed down from a parent component to a child component and allow you to pass data and methods throughout your application. Props are read-only and cannot be changed by the component that receives them. This is important to ensure data consistency throughout your application.

Here’s an example of how to use props in a component:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

// Use the component and pass a prop
<Welcome name="Sara" />

In this example, name is a prop being passed to the Welcome component, and inside the component, we access the prop as props.name.

2.3 Interactivity : Handling Events

Handling events in React is very similar to handling events on DOM elements in plain JavaScript, but there are a couple of key differences:

  1. React events are named using camelCase, rather than lowercase in plain JavaScript. For example, the onclick event in plain JavaScript is written as onClick in React.
  2. In React, you cannot return false to prevent default behavior. You must call preventDefault explicitly.

Here’s an example of an event handler in React:

import { useState } from 'react';

function ClickExample() {
  function handleClick() {
    alert("You clicked me!")
  }

  return (
    <div>
      <button onClick={handleClick}>
        Click me
      </button>
    </div>
  );
}

In this ClickCounter component, we’re handling the onClick event by displaying an alert with a message every time the button is clicked.

Event handling in React is an important concept because it allows you to make your UIs interactive and responsive to user input.

For more information about handling events in React, you can refer to the official React documentation on events.

2.4 State Management in React: An Overview

While props allow you to pass data down the component tree, the state allows components to have a memory and keep track of data specific to that component. State is similar to props, but it is private and fully controlled by the component.

State is primarily used to store information that may change over the lifetime of the component and needs to be kept track of. The state of a component can change over time, and whenever it does, the component updates itself. This is what we call a “re-render” of a component.

Here’s an example of how to use state in a component :

We can introduce state to a function component using the useState hook. (Hooks are special functions in React. We will learn more about them in the next chapter “Advanced Concepts”.)

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1)
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>
        Click me
      </button>
    </div>
  );
}

In this Counter component, we’re using state to keep track of how many times the user has clicked the button.

When the user clicks on the button, setCount updates the values of the count state variable, which triggers a re-render of the component. The component Counter renders with the new value of counter.

By understanding components, props, and state, you are well on your way to mastering the basics of React, which will play a pivotal role in your React Native journey. In the next section, we will delve deeper into React’s advanced concepts.

3. Deeper into React : Advanced Concepts

Having covered the basics, let’s dive into some of the more advanced aspects of React. These concepts, while more complex, offer greater control and efficiency in your applications, and are essential for a well-rounded understanding of React.

3.1 Understanding Hooks in React

Hooks are a relatively new addition to React that enable more features for functional components. They represent an alternative to writing class-based components, and offer a less complex syntax while still allowing for advanced features such as state and lifecycle methods.

There are several built-in hooks in React, including useState, useRef, useEffect, and useMemo, among others. We’ve already seen the useState hook in action.

useRef

Here’s an example of useRef, which is used to create a reference to a DOM element or a mutable instance variable that persists for the entire lifetime of the component. Here’s an example of how you might use useRef to focus on an input field when a button is clicked:

import React, { useRef } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);

  const onButtonClick = () => {
    // current property is a reference to the DOM element
    if(inputEl.current) inputEl.current.focus();
  };

  return (
    <div>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </div>
  );
}

export default TextInputWithFocusButton;

inputEl holds a reference pointing to the text input DOM element. The onButtonClick function, when called, will focus the text input if the ref is initialized.

This is very useful because remember that React Element in JSX are merely a virtual representation of the underlying DOM.

Sometimes, we need an escape hatch to actually manipulate the real DOM like in this example where we want to call the native method `focus()` on the input HTML element.

3.2 The React Lifecycle: A Brief Introduction to useEffect

In React, each component goes through a series of ‘lifecycle’ events that you can control by defining functions that will be called at different stages of a component’s life.

React lifecycle events are divided into three main phases:

  1. Mounting: This is when an instance of a component is being created and inserted into the DOM.
  2. Updating: An update can be caused by changes to props or state.
  3. Unmounting: This method is called when a component is being removed from the DOM.

To handle these lifecycle events, we use the useEffect hook. The useEffect hook is used to handle side effects in your components.

  1. Mounting: The useEffect hook with an empty array [] as the second argument is called when the component is created :
  useEffect(() => {
    // Your side effect code here
  }, []);
  1. Updating: A useEffect hook without an empty array as the second argument is called when the component is updated :
  useEffect(() => {
    // Your side effect code here
  });

If you only want to run the callback when certain values change (this can be state values or props values), you can pass those values in an array as the second argument to useEffect:

  useEffect(() => {
    // Your side effect code here
  }, [value1, value2]);
  1. Unmounting: To trigger a callback when the component is being removed from the DOM, return a cleanup function from your useEffect. This function will be called during unmount.
  useEffect(() => {
    // Your side effect code here

    return () => {
      // Cleanup code here
    };
  }, []);

Here is an example of

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Here, we use useEffect to update the page title every time the component is updated.

The component is updated when the users clicks on the button, which changes the state variable count. When setCount is executed, the component is updated, and the useEffect callback is triggered.

  • The component is updated when the users clicks on the button, which changes the state variable count.
  • When setCount is executed, the component is updated
  • The callback in useEffect is triggered.

3.3 Managing Data Flow with Context API

The Context API is a component structure provided by the React framework, which enables us to share specific forms of data across all levels of the application. It’s aimed at solving the problem of prop drilling, passing props from grandparent to child to grandchild, and so on.

Here’s how you can use the Context API to pass data around your application:

import React, { useContext } from 'react';

// Create a Context
const NumberContext = React.createContext();

// React.CreateContext returns a Provider and a Consumer. 

// We're using the Provider in an App component higher up in the component tree.
export default function App() {
  return (
    <NumberContext.Provider value={42}>
      <div>
        <Display />
      </div>
    </NumberContext.Provider>
  );
}

// We're using the Consumer in a Display component. It takes the value from the nearest Provider up the tree.
function Display() {
  const value = useContext(NumberContext);
  return <div>The answer to life, the universe, and everything is {value}.</div>
  );
}

Mastering these advanced concepts will provide you with a more complete understanding of React, and better prepare you for dealing with complex situations in React Native. In the next section, we’ll discuss practical tips for working with React and building your first application.

4. Working with React

Now that we’ve covered both basic and advanced concepts, it’s time to put theory into practice. In this section, we’ll walk you through creating a simple React application and share some tips for debugging your applications.

4.1 How to Create a Simple React App

Creating a new React application is straightforward with the create-react-app command-line tool. Here’s a step-by-step guide:

# 1. Install Node.js and npm if they're not already on your machine.

# 2. Install create-react-app globally with npm
npm install -g create-react-app

# 3. Create a new app
npx create-react-app my-app

# 4. Move into the app directory
cd my-app

# 5. Start the development server
npm start

This will create a new React application in a directory named my-app, and start a development server. You can now open your browser to http://localhost:3000 to see your app.

Now, you can start building your application by editing the App.js file in the src folder. Each time you save your changes, the browser will automatically update with the new output.

It is the time to learn by doing : now that you’ve set up your environment and created your first component, it’s time to learn more about React by building things. The official React documentation is an excellent resource and starting point. Other resources like Codecademy, freeCodeCamp, and Udemy offer tutorials and courses for all levels.

4.2 Tips for Debugging React Applications

Debugging is a critical skill for any developer. Here are some tips for debugging React applications:

  1. React Developer Tools: This is a browser extension available for both Chrome and Firefox. It allows you to inspect the React component hierarchies in the virtual DOM. You can select individual components and examine and edit their current props and state.
  2. Console Logs: The console.log() function is a quick and easy way to output the value of variables at any point in your code. You can use it to see what’s happening in your components.
  3. Use the Error Messages: React error messages usually do a great job of telling you where in your code the error occurred. If you encounter an error, start by reading the message closely.
  4. Breakpoints in the Browser Debugger: Most modern browsers come with built-in JavaScript debuggers. You can set breakpoints in your JavaScript code, which will pause execution and allow you to step through your code one line at a time and inspect variables at each point.

Remember, practice makes perfect. As you gain more experience, you’ll become more proficient at debugging and writing React code. In the next section, we will explore how your newfound React knowledge translates to React Native and the key differences between the two.

5. React and React Native: The Connection

By now, you’ve gained a solid understanding of React and have learned how to create and debug a React application. But how does this knowledge translate to React Native?

Let’s discuss the relationship between React and React Native, highlighting the key similarities and differences.

5.1 Understanding the Relationship between React and React Native

React and React Native share a lot in common. At their core, both libraries are used to build UIs using components. The concepts of state, props, and context, as well as the use of hooks and lifecycle methods, apply to both.

React Native, however, is designed specifically for mobile development and allows you to write code in JavaScript that is then translated to native code (Objective-C for iOS, Java for Android). This means that with React Native, you can write one application that works on multiple platforms.

5.2 Key Similarities

Here are some of the key similarities between React and React Native:

  1. Component-Based: Both React and React Native are based on a component architecture, allowing for reuse and better organization of code.
  2. State and Props: State and props are central concepts in both libraries. They allow you to manage data and pass it around your application.
  3. Lifecycle Methods and Hooks: Both libraries provide lifecycle methods in class components and hooks in functional components, allowing you to control what happens at different stages of a component’s life.
  4. Context API: Both React and React Native support the Context API, providing a way to pass data through the component tree without having to pass props down manually at every level.

5.3 Key Differences

While React and React Native share a lot of similarities, there are important differences to be aware of:

  1. Styling: In React, we style components using CSS. In React Native, we use a JavaScript object that resembles CSS.
  2. DOM vs. Native Components: React interacts with the HTML DOM, while React Native uses native components. This means that instead of using HTML elements like div, span, and h1, we use built-in components provided by React Native, such as View, Text, and Image.
  3. Navigation: Navigation in web apps is different from navigation in mobile apps. In React Native, we don’t have browser-like links. Instead, we use open-source libraries like React Navigation or React Native Navigation.
  4. Animations: While CSS animations can be used in React, React Native requires a different approach. We use Animated API or the Reanimated library for animations in React Native applications.

By understanding both the similarities and differences between React and React Native, you’ll be better equipped to leverage your React knowledge in the realm of React Native. In the next section, we’ll discuss the next steps on your journey to becoming a proficient React Native developer.

6. Conclusion

Congratulations on taking your first step into the world of React!

Understanding React concepts is a significant milestone in your journey to mastering React Native. Both libraries, while having their unique characteristics and targeting their respective platforms (websites and mobile apps) share the essential principle of building reusable UI components.

The best way to solidify your newfound knowledge is through consistent practice. Don’t be afraid to build your own small projects, or even contribute to open-source. The more you use React and React Native, the more comfortable you’ll become with the library.

In the upcoming articles, we’ll explore more about React Native, including its environment setup, the best libraries, navigation, and state management. Stay tuned!

And remember, if you ever get stuck or need help, the React and React Native communities are vibrant and welcoming places full of individuals who are ready to help. You’re never alone on this journey.

Thank you for reading, and we look forward to seeing you in our next post!

Note: If you liked this article or found it helpful, please share it with your friends and colleagues. Also, don’t forget to subscribe to our blog to receive our latest updates.


To further your understanding of React and its related technologies, explore some of our other articles:

Scroll to Top