Components in React| React Native Prerequisites

Learn via video courses
Topics Covered

Overview

React components are the essential building blocks of user interfaces in both web and mobile applications, enabling developers to create modular, reusable, and easy-to-maintain code. They define the structure, behavior, and appearance of different parts of an application, making them a prerequisite for building applications in React Native. This article covers the basics of React components, including the two types of components - React functional components and class-based components react - and provides examples and code snippets to illustrate their usage.

What are the Components in React?

Components in React are the reusable building blocks of a user interface. They define the structure, behavior, and appearance of different parts of a web or mobile application. Components can be thought of as individual pieces of a puzzle that can be combined to create a complete UI. React components are written in JavaScript and are modular, meaning they can be reused throughout the application. By using components, developers can create more maintainable and scalable code, as well as improve the overall user experience.

React Native uses the same component-based architecture as React, which means that the same principles apply when it comes to creating and using components. However, React Native components are specifically designed for mobile app development and have a slightly different syntax than regular React components. React Native components have access to a different set of APIs and UI components that are optimized for mobile platforms.

Class Based Components

Class-based components are defined using JavaScript classes that extend the base `React. Component class. They are used to create more complex components with more functionality, including the ability to manage state and lifecycle events.

Class-based components have a render() method, which returns the JSX code that defines the component's output. They also have a state object, which is used to store and update data that affects the component's behavior or appearance. State updates trigger a re-rendering of the component, resulting in an updated output.

Class components are more powerful and can be used to create stateful or container React Native components that can manage state and interact with other components.

Here's an example of a simple class-based component:

The ClassComponentExample class is defined as a subclass of the Component class, which allows it to take advantage of all the features provided by the React library. The render() method is then defined within the class, which returns a JSX expression that defines the output of the component.

Class-based components react are still widely used and supported, especially in older codebases.

Lifecycle Methods

React class-based components have several lifecycle methods that allow developers to define specific behavior at different points in the component's lifecycle. These methods can be used to perform actions like initializing the state, updating the component in response to changes in props or state, and cleaning up after the component is unmounted.

Class-based components react can be useful for more complex components that require state and lifecycle methods.

Here is an overview of some of the most commonly used lifecycle methods:

  • constructor(): This method is used to initialize the component's state and bind methods to the component's context. Here is an example of how to use it:

In this example, the constructor() method initializes the component's state to { count: 0 } and binds the handleClick() method to the component's context.

  • render(): This method returns a JSX expression that defines the component's output. Here is an example of how to use it:
  • componentDidMount(): This method is called after the component has been mounted (i.e., added to the DOM) and is often used to perform initialization tasks, such as fetching data from a server or setting up event listeners. Here is an example of how to use it:

In this example, componentDidMount() is used to fetch data from an API and update the component's state with the retrieved data.

  • componentDidUpdate(): This method is called whenever the component's props or state changes and is used to update the component in response to those changes. Here is an example of how to use it:

The componentDidUpdate method is called after the component's state has been updated. It compares the current count value with the previous count value and logs a message to the console if the count has changed.

  • componentWillUnmount(): This method is called just before the component is unmounted (i.e., removed from the DOM) and is used to perform any necessary cleanup tasks, such as removing event listeners or canceling pending requests.

In this example, componentDidMount() sets up a timer using setInterval(). The timer increments the count value in the component's state every second. When the component is unmounted, the componentWillUnmount() method is called and clears the timer using clearInterval(). This ensures that the timer is stopped and doesn't continue to run after the component is unmounted, preventing memory leaks.

React Native components built using class components can encapsulate complex functionality into reusable components.

Functional Components

Functional components are a type of component in React that are defined as functions instead of classes. They are a simpler way of creating components that don't require complex logic or state management. They are concise, easy to read, and don't require a lot of boilerplate code.

React Functional components are a simpler way to define React Native components and can be used to create stateless or presentational components.

Here's an example of a basic React functional component:

React Functional components can also take in props as input and return dynamic UI components based on those props. Here's an example:

Hooks

Hooks are a feature introduced in React 16.8 that allows React functional components to use state and lifecycle methods previously only available in class components. They are functions that enable you to use React state and other React features in functional components without writing a class. Class-based components of React are gradually being replaced by React functional components with hooks.

Understanding React Native components, along with the differences between functional and class components and the use of hooks, is essential for building robust and scalable mobile applications using React Native.

Here are some examples of hooks in React functional components:

  • useState: This hook allows you to add state to React functional components. It takes in an initial value and returns an array with the current state and a function to update the state.
  • useEffect: This hook allows you to perform side effects in React functional components. It takes in a function to execute and an optional array of dependencies. The function will be executed after the component is mounted and re-executed if any of the dependencies change.

In this example, we define a Timer React functional component that uses the useState and useEffect hooks. We define seconds as the current state and setSeconds as the function to update the state. We then use the useEffect hook to set up an interval that increments the seconds every second. The return function of useEffect clears the interval when the component is unmounted.

  • useMemo: useMemo is a hook in React that allows you to memoize the result of a function call and cache it. It is used to optimize performance by avoiding unnecessary calculations or expensive computations. The memoized value is only recalculated when the dependencies specified in the second argument of useMemo change.

In the above example, the expensiveCalculation is only recalculated when the list prop changes. The memoized value is stored and reused if the dependencies remain the same, optimizing the rendering performance.

  • useCallback: useCallback is a hook in React that returns a memoized version of the provided function. It is useful when passing callbacks to child components to prevent unnecessary re-renders of those components. The memoized callback is only changed when the dependencies specified in the second argument of useCallback change.

In the above example, the handleClick function is only recreated when the isClickable prop changes. By using useCallback, we can ensure that the callback reference remains the same unless its dependencies change, avoiding unnecessary re-renders of child components that receive this callback.

  • useRef: useRef is a hook in React that allows you to create a mutable reference that persists across re-renders of a component. It is commonly used to access and modify DOM elements or to store mutable values that don't trigger re-renders.

In the above example, inputRef is used to create a reference to the input element. The focusInput function uses the current property of the inputRef to access and focus the input element. The value of inputRef.current persists across re-renders, allowing us to manipulate the DOM element without triggering a re-render.

FAQs

Q. What is the difference between functional and class components in React?

A. React Functional components are JavaScript functions that return React elements, while class components are ES6 classes that extend React's component class. React Functional components are simpler and more concise, but class components offer more features, such as lifecycle methods and state management.

Q. What are React hooks?

A. React hooks are functions that allow React functional components to use state and lifecycle methods. They were introduced in React 16.8 as a way to simplify state management and lifecycle management in React functional components.

Q. Can I use both functional and class components in the same React app?

A. Yes, you can use both functional and class components in the same React app. In fact, many React apps use a combination of both types of components to take advantage of their different features and strengths.

Q. Can I reuse the same component in multiple parts of my application?

A. Yes, that's one of the main benefits of using components in React! By creating reusable components, you can avoid writing the same code over and over again for different parts of your application. Instead, you can define a component once and then use it as many times as you need throughout your app.

Conclusion

  • Components are the fundamental building blocks of user interfaces in React and React Native.
  • They allow developers to create modular, reusable, and maintainable code.
  • There are two types of components in React: functional and class-based.
  • React Functional components are simpler and more lightweight than class-based components and can use hooks to add state and lifecycle functionality.
  • Class-based components offer more features and are better suited for larger, more complex applications.
  • Understanding components is a crucial prerequisite for learning React Native, a popular framework for building mobile applications using React Native Components.
  • By mastering React components, developers can create high-quality, scalable, and performant web and mobile applications with ease.