Categories
Angular JavaScript Performance React

“Boosting UI Performance: Best Practices and Strategies”

Reading Time: 10 minutes

As a JavaScript developer, there are several key considerations you should make when writing logic for a high-performance user interface. Here are some of the most important ones:

  1. Reduce the number of DOM manipulations: Manipulating the DOM can be a very slow operation, so you should try to reduce the number of times you access or modify it. One way to do this is to cache DOM elements that you’ll be accessing frequently, instead of looking them up every time.
  2. Use event delegation: Instead of attaching event listeners to every element on the page, you can use event delegation to attach a single event listener to a parent element and listen for events as they bubble up. This can improve performance by reducing the number of event listeners attached to the page.
  3. Avoid unnecessary re-renders: When updating the UI, try to avoid unnecessary re-renders. For example, if you’re updating a list of items, only update the items that have changed instead of re-rendering the entire list.
  4. Use requestAnimationFrame: Use requestAnimationFrame instead of setInterval or setTimeout for animations and other time-based updates. This can help ensure that your updates are synchronized with the browser’s rendering process, leading to smoother animations and better performance. requestAnimationFrame is a browser API that allows you to schedule an animation or render update for the next frame of the browser’s rendering pipeline. It can be used to improve the performance of animations and ensure that they are rendered at the optimal time.
  5. Minimize network requests: Minimize the number of network requests your app makes. This can be achieved by optimizing images and other assets, caching data locally, and reducing unnecessary requests.
  6. Optimize for mobile: Make sure your UI is optimized for mobile devices, which typically have slower processors and less memory than desktops. This means avoiding heavy animations, minimizing the use of large images and videos, and optimizing for touch-based interactions.

By taking these considerations into account, you can create a high-performance user interface that provides a great user experience.


Here are some techniques you can use to reduce the number of DOM manipulations in your application:

  1. Use the Angular Change Detection mechanism: Angular provides a powerful change detection mechanism that automatically updates the view when data changes. By using this mechanism, you can avoid manually updating the DOM and improve performance.
  2. Use the ng-container directive: The ng-container directive allows you to group multiple elements together without actually creating an additional element in the DOM. This can help reduce the number of elements in the DOM and improve performance.
  3. Use the ngIf and ngSwitch directives: The ngIf and ngSwitch directives allow you to conditionally render elements in the DOM based on certain conditions. This can help reduce the number of elements in the DOM and improve performance.
  4. Use the trackBy function: When working with ngFor loops, use the trackBy function to track changes to individual items in the loop. This can help Angular identify which elements have changed and avoid unnecessary DOM updates.
  5. Use the Renderer2 service: When you do need to manipulate the DOM, use the Renderer2 service provided by Angular. This service provides a platform-agnostic way of interacting with the DOM and can help improve performance.

By using these techniques, you can reduce the number of DOM manipulations in your Angular application and improve performance.


Here are some of the most effective ways to reduce re-render of your application:

  1. Use the OnPush change detection strategy: The OnPush change detection strategy tells Angular to only check for changes when input properties have changed or when an event is triggered. This can help reduce the number of unnecessary re-renders and improve performance.
  2. Use the async pipe: When working with observables in your Angular application, use the async pipe instead of manually subscribing and unsubscribing to the observable. The async pipe automatically subscribes and unsubscribes to the observable, which can help reduce the number of unnecessary re-renders.
  3. Use pure pipes: Pure pipes are stateless functions that transform input values into output values. They only re-run when the input value changes, which can help reduce the number of unnecessary re-renders.
  4. Use ngDoCheck() hook: If you need to perform custom change detection logic, you can use the ngDoCheck() lifecycle hook. This hook allows you to implement your own change detection algorithm and can help reduce the number of unnecessary re-renders.
  5. Use ChangeDetectorRef: If you need to manually trigger change detection in your Angular application, you can use the ChangeDetectorRef service. This service allows you to manually trigger change detection for a component or its children, which can help reduce the number of unnecessary re-renders.

Here’s how you can use event delegation in your application by using the Angular event binding syntax and handling events at the component level.

Here are the steps to implement event delegation in your Angular application:

  1. Add an event listener to the parent element: Add an event listener to a parent element using the Angular event binding syntax. For example, you can add a click event listener to a parent element like this:
<div (click)="handleClick($event)">
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
</div>
  1. Handle the event at the component level: In the component class, implement the handleClick() method to handle the click event. You can use the $event object to get information about the event, such as the target element.
export class MyComponent {
  handleClick(event: MouseEvent) {
    const target = event.target as HTMLElement;
    if (target.nodeName === 'BUTTON') {
      // Handle button click here
    }
  }
}
  1. Conditionally handle the event: In the handleClick() method, you can conditionally handle the event based on the target element. For example, you can check if the target element is a button element and perform some action accordingly.

By using event delegation, you can reduce the number of event listeners in your Angular application and improve performance.


Here’s how you can minimize network requests in your application by using several techniques. Here are some of the most effective ones:

  1. Use HTTP Interceptors: HTTP Interceptors allow you to intercept HTTP requests and responses and add custom logic. You can use interceptors to cache responses, modify headers, or add authentication tokens, which can help reduce the number of network requests.
  2. Use lazy loading: Lazy loading allows you to load parts of your application on demand. By loading only the necessary components and modules, you can reduce the initial load time and the number of network requests.
  3. Use server-side rendering (SSR): Server-side rendering allows you to render your Angular application on the server before sending it to the client. This can help reduce the initial load time and the number of network requests.
  4. Use HTTP caching: HTTP caching allows you to cache responses from your server and reuse them for subsequent requests. By caching responses, you can reduce the number of network requests and improve performance.
  5. Use WebSockets: WebSockets allow you to establish a persistent connection between the client and the server. By using WebSockets, you can reduce the number of HTTP requests and improve performance.
  6. Optimize images and assets: Optimize images and assets by compressing them and using appropriate file formats. This can help reduce the size of network requests and improve performance.

By using these techniques, you can minimize network requests in your Angular application and improve performance.


Optimizing the performance of a React application is a crucial part of the development process, and it involves several techniques to ensure that the application is fast and responsive for the user. Here are some ways to optimize the performance of your React application:

  1. First Paint: The first paint is a crucial metric for the user experience, and it determines how quickly the user can see the initial content of the application. You can optimize the first paint time of your React application by using server-side rendering (SSR) or static site generation (SSG) techniques.

SSR involves rendering the initial HTML on the server and then sending it to the client, which reduces the time it takes for the user to see the content. SSG involves pre-rendering the entire website at build time, which can improve the performance by reducing the number of requests to the server.

  1. User Interaction: User interaction is a critical aspect of any application, and the performance of the application can significantly impact the user experience. You can optimize user interaction in your React application by using virtual DOM, avoiding unnecessary re-renders, and minimizing network requests.

The virtual DOM is a lightweight representation of the actual DOM, which allows React to update only the necessary parts of the UI when changes occur. You can avoid unnecessary re-renders by using the shouldComponentUpdate lifecycle method, which compares the previous and current props and state to determine if the component needs to update.

  1. Network Performance: Network performance is another critical factor that affects the performance of a React application. You can optimize network performance by using code splitting, lazy loading, and caching.

Code splitting involves splitting your code into smaller chunks and loading them on demand, which can reduce the initial load time of your application. Lazy loading allows you to load parts of your application on demand, which can reduce the number of requests to the server and improve performance. Caching involves storing data locally or on the server, which can reduce the number of requests and improve the performance.

  1. Fast Rerender: Fast rerender is a critical aspect of any React application, and it ensures that the UI is fast and responsive when the user interacts with it. You can optimize fast rerender by using memoization, useCallback, and useMemo.

Memoization involves caching the results of expensive function calls, which can improve the performance by reducing the number of times the function is called. useCallback and useMemo are hooks that allow you to memoize functions and values, which can reduce unnecessary re-renders.

Overall, optimizing the performance of a React application involves several techniques, including server-side rendering, virtual DOM, code splitting, and memoization. By applying these techniques, you can ensure that your application is fast, responsive, and provides an excellent user experience.


Here are some code snippets that demonstrate how to implement the optimization techniques I mentioned earlier:

  1. Server-Side Rendering: Server-side rendering involves rendering the initial HTML on the server and then sending it to the client. Here’s an example of how to implement server-side rendering in a React application using the ReactDOMServer module:
import React from 'react';
import ReactDOMServer from 'react-dom/server';

function App() {
  return <div>Hello, world!</div>;
}

const html = ReactDOMServer.renderToString(<App />);

console.log(html); // <div data-reactroot="">Hello, world!</div>
  1. Virtual DOM: The virtual DOM is a lightweight representation of the actual DOM, which allows React to update only the necessary parts of the UI when changes occur. React uses VDOM internally, hence example is mere representation. Here’s an example of how to use the virtual DOM in a React application:
import React, { useState } from 'react';

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

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

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

In the above example, the useState hook creates a state variable called count and a function called setCount, which updates the state variable. The handleClick function updates the state variable count when the user clicks the button. React uses the virtual DOM to update only the necessary parts of the UI when the state variable count changes.

  1. Code Splitting: Code splitting involves splitting your code into smaller chunks and loading them on demand. Here’s an example of how to implement code splitting in a React application using the React.lazy function:
import React, { lazy, Suspense } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

In the above example, the React.lazy function creates a new component called LazyComponent, which is loaded on demand when the user accesses the component. The Suspense component shows a loading spinner while the component is being loaded.

  1. Memoization: Memoization involves caching the results of expensive function calls. Here’s an example of how to use memoization in a React application using the useMemo hook:
import React, { useState, useMemo } from 'react';

function fibonacci(n) {
  if (n <= 1) {
    return n;
  }

  return fibonacci(n - 1) + fibonacci(n - 2);
}

function Fibonacci() {
  const [n, setN] = useState(0);
  const result = useMemo(() => fibonacci(n), [n]);

  function handleChange(e) {
    setN(parseInt(e.target.value));
  }

  return (
    <div>
      <input type="number" value={n} onChange={handleChange} />
      <p>{result}</p>
    </div>
  );
}

In the above example, the fibonacci function calculates the Fibonacci sequence, which is an expensive operation. The useMemo hook caches the result of the function call and only recalculates it when the value of n changes. This improves the performance of the application by reducing the number of times the function is called.


Amazon, like many other large-scale web applications, uses a variety of application code-level techniques to build a fast-performing UI. Here are some of the techniques Amazon employs:

  1. Code Splitting: Amazon uses code splitting to split their application code into smaller chunks that can be loaded on demand, which reduces the initial load time and improves the perceived performance of the website.
  2. Memoization: Amazon uses memoization to cache the results of expensive function calls, which reduces the time required to compute the same result multiple times.
  3. Virtualization: Amazon uses virtualization techniques, such as React’s virtual DOM, to minimize the number of DOM updates required, which reduces the time required to update the UI and improves the perceived performance of the website.
  4. Debouncing and Throttling: Amazon uses debouncing and throttling techniques to limit the number of events generated by the user, such as scroll and resize events, which reduces the number of unnecessary updates to the UI and improves the perceived performance of the website.
  5. Avoiding Synchronous Operations: Amazon avoids synchronous operations, such as synchronous XHR requests, which can block the main thread and reduce the perceived performance of the website.
  6. Efficient Data Structures: Amazon uses efficient data structures, such as hash tables and binary search trees, to store and access data, which reduces the time required to search and manipulate data.
  7. Optimal Algorithms: Amazon uses optimal algorithms, such as sorting and searching algorithms, to perform complex operations efficiently, which reduces the time required to perform these operations.
  8. Progressive Web Apps: Amazon uses progressive web app techniques, such as service workers and caching, to provide an app-like experience to users, which reduces the time required to load the website on subsequent visits and improves the perceived performance of the website.

These are just a few of the application code-level techniques Amazon uses to build a fast-performing UI. By employing a combination of these techniques, Amazon is able to provide a fast and responsive user experience for its customers.


Code splitting is a technique used to split large chunks of code into smaller, more manageable pieces, which can be loaded on-demand as needed. This can improve the performance of a web application by reducing the initial load time and improving the perceived performance.

Here are examples of code splitting in React and Angular:

Code Splitting in React

In React, code splitting can be achieved using the dynamic import() function. Here’s an example:

import React, { lazy, Suspense } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

export default App;

In this example, we’re using the lazy() function to dynamically import the LazyComponent component when it’s needed. We’re also using the Suspense component to show a loading indicator while the component is being loaded.

Code Splitting in Angular

In Angular, code splitting can be achieved using the loadChildren property in the route configuration. Here’s an example:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'lazy',
    loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

In this example, we’re using the loadChildren property to dynamically load the LazyModule module when the user navigates to the /lazy route. The import() function is used to load the module asynchronously.

Both React and Angular provide ways to implement code splitting, making it easier to manage large codebases and improve the performance of web applications.

Debouncing and throttling are techniques used to limit the number of times a function is executed in a given time period. This can improve the performance of a web application by reducing the number of unnecessary updates to the UI.

Here are examples of debouncing and throttling in React and Angular:

Debouncing and Throttling in React

In React, debouncing and throttling can be achieved using the lodash library. Here’s an example of debouncing an input event:

import React, { useState } from 'react';
import { debounce } from 'lodash';

function App() {
  const [value, setValue] = useState('');

  const handleInputChange = debounce((event) => {
    setValue(event.target.value);
  }, 500);

  return (
    <div>
      <input type="text" onChange={handleInputChange} />
      <p>Value: {value}</p>
    </div>
  );
}

export default App;

In this example, we’re using the debounce() function from the lodash library to limit the number of times the handleInputChange() function is called in a 500-millisecond time period.

Debouncing and Throttling in Angular

In Angular, debouncing, and throttling can be achieved using the rxjs library. Here’s an example of throttling a scroll event:

import { Component, HostListener } from '@angular/core';
import { throttleTime } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: `
    <div [style.height.px]="height" [style.background-color]="color"></div>
  `
})
export class AppComponent {
  height = 0;
  color = 'red';

  @HostListener('window:scroll')
  onScroll() {
    this.height = window.scrollY;
    this.color = 'blue';
    this.throttledUpdate();
  }

  throttledUpdate = throttleTime(() => {
    console.log('Updating...');
  }, 500);
}

In this example, we’re using the throttleTime() operator from the rxjs/operators module to limit the number of times the throttledUpdate() function is called in a 500 millisecond time period.

Both React and Angular provide ways to implement debouncing and throttling, making it easier to limit the number of times a function is executed in a given time period and improve the performance of web applications.

Categories
Code Quality Jest React Unit Testing

Unit Testing for React: A Comprehensive Introduction

Reading Time: 15 minutes

Are you tired of debugging your React app and fixing bugs that could have been caught earlier? Unit testing is the solution! With unit testing, you can ensure that your code works as intended, and catch issues early on. In this blog post, we’ll explore different ways to get started with unit testing a React app using Jest.

Jest is a JavaScript testing framework developed by Facebook. It is widely used in the React community and provides an easy-to-use interface for writing tests. Let’s explore some examples of how you can get started with Jest in your React app.

  1. Setting up Jest in a React app

First, you need to set up Jest in your React app. You can do this by installing Jest as a dev dependency in your project:

npm install --save-dev jest

Once installed, create a jest.config.js file in the root of your project:

module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
};

This sets up the Jest environment and includes the @testing-library/jest-dom package, which provides additional matchers for testing React components.

  1. Writing your first unit test

Now that Jest is set up in your project, it’s time to write your first unit test. Let’s say you have a simple component that displays a greeting message:

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

To test this component, create a Greeting.test.js file and write your first test:

import React from 'react';
import { render } from '@testing-library/react';
import Greeting from './Greeting';

test('renders greeting message', () => {
  const { getByText } = render(<Greeting name="John" />);
  const greetingElement = getByText(/Hello, John!/i);
  expect(greetingElement).toBeInTheDocument();
});

In this test, we render the Greeting component with a name prop of “John”. We then use getByText from the @testing-library/react package to find the element that contains the greeting message. Finally, we use expect to assert that the greeting element is in the document.

  1. Testing component behavior

In addition to testing component rendering, you can also test component behavior. Let’s say you have a simple counter component that increments a count when a button is clicked:

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

  const handleIncrement = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
}

To test the behavior of this component, create a Counter.test.js file and write your test:

import React from 'react';
import { fireEvent, render } from '@testing-library/react';
import Counter from './Counter';

test('increments count when button is clicked', () => {
  const { getByText } = render(<Counter />);
  const countElement = getByText(/Count: 0/i);
  const incrementButton = getByText(/Increment/i);

  fireEvent.click(incrementButton);

  expect(countElement).toHaveTextContent('Count: 1');
});

In this test, we render the Counter component and find the elements that contain the count and increment button. We then use fireEvent.click to simulate a click on the increment button. Finally, we use expect to assert that the count element has been updated to display a count of 1.

  1. Testing asynchronous code

What about components that fetch data from an API? Jest provides an easy way to test asynchronous code using async and await. Let’s say you have a component that fetches a list of users from an API:

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    async function fetchUsers() {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      const data = await response.json();
      setUsers(data);
    }

    fetchUsers();
  }, []);

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

To test this component, create a UserList.test.js file and write your test:

import React from 'react';
import { render, waitFor } from '@testing-library/react';
import UserList from './UserList';

test('displays list of users', async () => {
  const { getByText } = render(<UserList />);
  await waitFor(() => getByText(/Leanne Graham/i));
  expect(getByText(/Leanne Graham/i)).toBeInTheDocument();
});

In this test, we render the UserList component and use waitFor from the @testing-library/react package to wait for the list of users to be fetched and rendered. We then use expect to assert that the name “Leanne Graham” is in the document.

  1. Mocking dependencies

What if your component depends on an external library or API? Jest provides a way to mock these dependencies in your tests. Let’s say you have a component that depends on the axios library to fetch data:

import axios from 'axios';

function TodoList() {
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    async function fetchTodos() {
      const response = await axios.get('https://jsonplaceholder.typicode.com/todos');
      setTodos(response.data);
    }

    fetchTodos();
  }, []);

  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  );
}

To test this component, create a TodoList.test.js file and mock the axios library:

import React from 'react';
import { render } from '@testing-library/react';
import axios from 'axios';
import TodoList from './TodoList';

jest.mock('axios');

test('displays list of todos', async () => {
  const mockData = [
    { id: 1, title: 'Todo 1' },
    { id: 2, title: 'Todo 2' },
  ];

  axios.get.mockResolvedValue({ data: mockData });

  const { getByText } = render(<TodoList />);
  expect(getByText(/Todo 1/i)).toBeInTheDocument();
  expect(getByText(/Todo 2/i)).toBeInTheDocument();
});

In this test, we used jest.mock to mock the axios library. We then create some mock data and use axios.get.mockResolvedValue to mock the response from the API. Finally, we render the TodoList component and use expect to assert that the mock data is in the document.

Unit testing your React app with Jest is essential in ensuring your code works as intended and catching issues early on. By following these examples, you’ll be well on your way to writing effective and efficient unit tests for your React components.

Here are more examples from the basic to intermediate level, this should cover most of the scenarios one would encounter in day-to-day development tasks –

Example 1. Simplest Component

Let’s create a simple component and write a test for it. Create a new file MyComponent.jsx in your src folder and add the following code:

import React from 'react';

function MyComponent({ name }) {
  return (
    <div>
      <h1>Hello, {name}!</h1>
    </div>
  );
}

export default MyComponent;

Now, let’s write a test for this component. Create a new file MyComponent.test.jsx in the same directory and add the following code:

import React from 'react';
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
  it('renders the name prop', () => {
    const { getByText } = render(<MyComponent name="John" />);
    expect(getByText('Hello, John!')).toBeInTheDocument();
  });
});

Let’s go over what we just did.

We imported render from @testing-library/react to render our component in a test environment. We also imported our component, MyComponent.

We used the describe function to group our tests together. In this case, we only have one test, so we only need one it function.

In our test, we render our component with a name prop of “John”. We use the getByText function from @testing-library/react to check if the text “Hello, John!” is present in the rendered component.

Finally, we use the expect function to check if our assertion is true.

Example 2. Testing Component State

Let’s create a component that manages state, and test its behavior when the state changes. Create a new file Counter.jsx in your src folder and add the following code:

import React, { useState } from 'react';

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

  const handleClick = () => {
    setCount(count + 1);
  };

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

export default Counter;

This is a simple component that displays a counter and a button. When the button is clicked, the counter increments by one.

Now let’s write a test for this component. Create a new file Counter.test.jsx in the same directory and add the following code:

import React from 'react';
import { fireEvent, render } from '@testing-library/react';
import Counter from './Counter';

describe('Counter', () => {
  it('increments the counter on button click', () => {
    const { getByText } = render(<Counter />);
    const button = getByText('Click me');
    fireEvent.click(button);
    expect(getByText('You clicked 1 times')).toBeInTheDocument();
    fireEvent.click(button);
    expect(getByText('You clicked 2 times')).toBeInTheDocument();
  });
});


Let’s break down this test. We render our `Counter` component using `render` from `@testing-library/react`. We then use `getByText` to get a reference to the button element. We simulate a click event on the button using `fireEvent.click`. We then use `getByText` to check if the text “You clicked 1 times” is present in the rendered component. We simulate another click event on the button and check if the text “You clicked 2 times” is present. ## Testing component props Let’s create a component that takes props and test its behavior with different props. Create a new file `Greeting.jsx` in your `src` folder and add the following code:

import React from 'react';

function Greeting({ name }) {
  return (
    <div>
      <p>Hello, {name}!</p>
    </div>
  );
}

export default Greeting;

This is a simple component that displays a greeting message with the given name prop.

Now let’s write a test for this component. Create a new file Greeting.test.jsx in the same directory and add the following code:

import React from 'react';
import { render } from '@testing-library/react';
import Greeting from './Greeting';

describe('Greeting', () => {
  it('renders the name prop', () => {
    const { getByText } = render(<Greeting name="John" />);
    expect(getByText('Hello, John!')).toBeInTheDocument();
  });

  it('renders "World" if no name prop is passed', () => {
    const { getByText } = render(<Greeting />);
    expect(getByText('Hello, World!')).toBeInTheDocument();
  });
});

In this test, we have two test cases.

The first test case checks if the component renders the name prop correctly. We render the component with a name prop of “John” and check if the text “Hello, John!” is present in the rendered component.

The second test case checks if the component renders the default message “Hello, World!” if no name prop is passed. We render the component without any props and check if the text “Hello, World!” is present in the rendered component.

Example 3. Testing Component Events

Let’s create a component that fires an event and test its behavior when the event is triggered. Create a new file Form.jsx in your src folder and add the following code:

import React, { useState } from 'react';

function Form() {
  const [inputValue, setInputValue] = useState('');

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`You submitted: ${inputValue}`);
  };

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={inputValue} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default Form;

This is a simple form component that takes input from the user and shows an alert when the form is submitted.

Now let’s write a test for this component. Create a new file Form.test.jsx in the same directory and add the following code:

import React from 'react';
import { fireEvent, render } from '@testing-library/react';
import Form from './Form';

describe('Form', () => {
  it('shows an alert when the form is submitted', () => {
  const { getByLabelText, getByText } = render(<Form />);
  const input = getByLabelText('Name:');
  const submitButton = getByText('Submit');
  fireEvent.change(input, { target: { value: 'John' } });
  fireEvent.click(submitButton);

  expect(window.alert).toHaveBeenCalledWith('You submitted: John');
  });
});


In this test, we render the `Form` component and get references to the input and submit button using `getByLabelText` and `getByText`. We simulate a change event on the input field with `fireEvent.change` and pass an object that contains the value we want to set for the input. We then simulate a click event on the submit button using `fireEvent.click`. Finally, we check if the `window.alert` method was called with the expected message “You submitted: John”. Note that we have to mock the `window.alert` method using `jest.spyOn` before running this test.

Example 4. Testing a Component with a Third-party Library

To test a component that uses react-data-grid, you can create a test file called Table.test.jsx and add the following code:

import React from 'react';
import { render } from '@testing-library/react';
import ReactDataGrid from 'react-data-grid';
import Table from './Table';

describe('Table', () => {
  it('renders a grid with data', () => {
    const data = [
      { id: 1, name: 'John', age: 25 },
      { id: 2, name: 'Jane', age: 30 },
      { id: 3, name: 'Bob', age: 40 },
    ];
    const columns = [
      { key: 'id', name: 'ID' },
      { key: 'name', name: 'Name' },
      { key: 'age', name: 'Age' },
    ];

    const { container } = render(<Table data={data} columns={columns} />);
    const grid = container.querySelector('.react-grid-Grid');

    expect(grid).toBeInTheDocument();
    expect(grid).toHaveClass('react-grid-Grid');
    expect(grid).toHaveAttribute('role', 'grid');
    expect(grid).toHaveAttribute('aria-rowcount', '4'); // 3 data rows + 1 header row
  });

  it('displays the correct data in the grid', () => {
    const data = [
      { id: 1, name: 'John', age: 25 },
      { id: 2, name: 'Jane', age: 30 },
      { id: 3, name: 'Bob', age: 40 },
    ];
    const columns = [
      { key: 'id', name: 'ID' },
      { key: 'name', name: 'Name' },
      { key: 'age', name: 'Age' },
    ];

    const { getAllByRole } = render(<Table data={data} columns={columns} />);
    const rows = getAllByRole('row');

    expect(rows.length).toBe(4); // 3 data rows + 1 header row

    // Check header row
    const headerRow = rows[0];
    const headerCells = headerRow.querySelectorAll('[role="columnheader"]');

    expect(headerCells.length).toBe(3);
    expect(headerCells[0]).toHaveTextContent('ID');
    expect(headerCells[1]).toHaveTextContent('Name');
    expect(headerCells[2]).toHaveTextContent('Age');

    // Check data rows
    const dataRows = rows.slice(1);
    const firstDataRowCells = dataRows[0].querySelectorAll('[role="gridcell"]');

    expect(firstDataRowCells.length).toBe(3);
    expect(firstDataRowCells[0]).toHaveTextContent('1');
    expect(firstDataRowCells[1]).toHaveTextContent('John');
    expect(firstDataRowCells[2]).toHaveTextContent('25');
  });
});

In this test file, we create two tests: one to check if the Table component renders a grid with the correct attributes and one to check if the grid displays the correct data.

To render the Table component, we pass in some sample data and column definitions as props. We then use the render function from the @testing-library/react package to get a reference to the container that holds the rendered component.

Example 5. Testing a Component with Uses a Service

Let’s say you have a component called PostsList which displays a list of blog posts fetched from a backend API. The component uses a service called postService to fetch the data from the backend.

To test the PostsList component, you can create a test file called PostsList.test.jsx and add the following code:

import React from 'react';
import { render, waitFor } from '@testing-library/react';
import PostsList from './PostsList';
import postService from './postService';

jest.mock('./postService');

describe('PostsList', () => {
  it('displays a list of blog posts', async () => {
    const mockPosts = [
      { id: 1, title: 'First Post', body: 'This is the first post' },
      { id: 2, title: 'Second Post', body: 'This is the second post' },
      { id: 3, title: 'Third Post', body: 'This is the third post' },
    ];
    postService.getPosts.mockResolvedValue(mockPosts);

    const { getByText } = render(<PostsList />);
    const firstPostTitle = await waitFor(() => getByText('First Post'));

    expect(firstPostTitle).toBeInTheDocument();
    expect(getByText('Second Post')).toBeInTheDocument();
    expect(getByText('Third Post')).toBeInTheDocument();
  });

  it('displays an error message if the posts fail to load', async () => {
    const errorMessage = 'Failed to load posts';
    postService.getPosts.mockRejectedValue(new Error(errorMessage));

    const { getByText } = render(<PostsList />);
    const error = await waitFor(() => getByText(errorMessage));

    expect(error).toBeInTheDocument();
  });
});

In this test file, we create two tests: one to check if the PostsList component displays a list of blog posts fetched from the backend, and one to check if the component displays an error message if the posts fail to load.

To mock the postService module, we use the jest.mock function to replace the module with a mock implementation. In this case, we mock the getPosts function to return a mock array of blog posts.

In the first test, we render the PostsList component and wait for the posts to load using the waitFor function from @testing-library/react. We then check if the component renders the expected post titles using the getByText function from @testing-library/react.

In the second test, we mock the getPosts function to throw an error, simulating a failed API call. We then render the PostsList component and wait for the error message to appear using the waitFor function. We then check if the error message is displayed using the getByText function.

Example 6. Testing a component that renders different templates based on conditions.

Here’s an example of a component that renders different components based on a condition and uses the react-render-plugin library for testing:

import React from 'react';
import { renderPlugin } from 'react-render-plugin';

const ComponentWithConditionalRendering = ({ type }) => {
  if (type === 'A') {
    return <ComponentA />;
  } else if (type === 'B') {
    return <ComponentB />;
  } else {
    return <ComponentC />;
  }
};

const ComponentA = () => {
  return <div>Component A</div>;
};

const ComponentB = () => {
  return <div>Component B</div>;
};

const ComponentC = () => {
  return <div>Component C</div>;
};

describe('ComponentWithConditionalRendering', () => {
  it('should render ComponentA when type is A', () => {
    const { getByText } = renderPlugin(
      <ComponentWithConditionalRendering type="A" />
    );
    expect(getByText('Component A')).toBeInTheDocument();
  });

  it('should render ComponentB when type is B', () => {
    const { getByText } = renderPlugin(
      <ComponentWithConditionalRendering type="B" />
    );
    expect(getByText('Component B')).toBeInTheDocument();
  });

  it('should render ComponentC when type is neither A nor B', () => {
    const { getByText } = renderPlugin(
      <ComponentWithConditionalRendering type="C" />
    );
    expect(getByText('Component C')).toBeInTheDocument();
  });
});

In this example, the ComponentWithConditionalRendering component takes a type prop and renders different components based on the value of the type prop. We are using the react-render-plugin library to test this component.

In our tests, we render the ComponentWithConditionalRendering component with different type props and check that the correct component is rendered based on the value of the type prop. We use the getByText method from react-render-plugin to check that the correct component is rendered based on its text content.

Note that in this example, we only have three possible types (A, B, or any other value), but this approach can be extended to handle more complex conditions and multiple components.

Example 7. Testing a .tsx component using react-testing-library

Here’s another example of a React component that renders different components based on different conditions and is tested using react-testing-library:

import React from 'react';
import { render } from 'react-testing-library';
import { LibraryComponent } from 'library';

const ComponentToTest = () => {
  const [isConditionMet, setIsConditionMet] = React.useState(false);

  return (
    <div>
      {isConditionMet ? (
        <div>Rendered when condition is true</div>
      ) : (
        <div>Rendered when condition is false</div>
      )}
      <button onClick={() => setIsConditionMet(!isConditionMet)}>
        Toggle Condition
      </button>
      <LibraryComponent />
    </div>
  );
};

describe('ComponentToTest', () => {
  it('renders the component from the library', () => {
    const { getByTestId } = render(<ComponentToTest />);
    expect(getByTestId('library-component')).toBeInTheDocument();
  });

  it('renders "Rendered when condition is false" when condition is false', () => {
    const { getByText } = render(<ComponentToTest />);
    expect(getByText('Rendered when condition is false')).toBeInTheDocument();
  });

  it('renders "Rendered when condition is true" when condition is true', () => {
    const { getByText, getByRole } = render(<ComponentToTest />);
    const toggleButton = getByRole('button');
    toggleButton.click();
    expect(getByText('Rendered when condition is true')).toBeInTheDocument();
  });
});

In this example, the ComponentToTest renders a button to toggle the isConditionMet state between true and false, and conditionally renders different components based on that state. The react-testing-library is used to render the component and make assertions about the rendered output in the test cases.

Example 8. An example of a test for a component that makes an API call using Axios and checks the HTTP status and response:

import React from 'react';
import axios from 'axios';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

jest.mock('axios');

describe('MyComponent', () => {
  it('should display the data fetched from the API', async () => {
    const data = { id: 1, name: 'John Doe' };
    const response = { data, status: 200 };
    axios.get.mockResolvedValue(response);

    render(<MyComponent />);

    const idElement = await screen.findByText(`ID: ${data.id}`);
    const nameElement = await screen.findByText(`Name: ${data.name}`);

    expect(idElement).toBeInTheDocument();
    expect(nameElement).toBeInTheDocument();
    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(axios.get).toHaveBeenCalledWith('https://example.com/api/data');
  });

  it('should display an error message if the API call fails', async () => {
    const error = new Error('API call failed');
    axios.get.mockRejectedValue(error);

    render(<MyComponent />);

    const errorElement = await screen.findByText('Error: API call failed');

    expect(errorElement).toBeInTheDocument();
    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(axios.get).toHaveBeenCalledWith('https://example.com/api/data');
  });

  it('should display a loading message while the API call is in progress', async () => {
    axios.get.mockImplementation(() => new Promise(() => {}));

    render(<MyComponent />);

    const loadingElement = await screen.findByText('Loading...');

    expect(loadingElement).toBeInTheDocument();
    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(axios.get).toHaveBeenCalledWith('https://example.com/api/data');
  });

  it('should handle a 404 response status', async () => {
    const errorResponse = {
      response: {
        status: 404,
        data: { message: 'Resource not found' }
      }
    };
    axios.get.mockRejectedValue(errorResponse);

    render(<MyComponent />);

    const errorElement = await screen.findByText('Error: Resource not found');

    expect(errorElement).toBeInTheDocument();
    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(axios.get).toHaveBeenCalledWith('https://example.com/api/data');
  });

  it('should handle a 500 response status', async () => {
    const errorResponse = {
      response: {
        status: 500,
        data: { message: 'Internal server error' }
      }
    };
    axios.get.mockRejectedValue(errorResponse);

    render(<MyComponent />);

    const errorElement = await screen.findByText('Error: Internal server error');

    expect(errorElement).toBeInTheDocument();
    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(axios.get).toHaveBeenCalledWith('https://example.com/api/data');
  });
});

In this example, we are testing a component called MyComponent that makes an API call using Axios. We are using Jest to mock the Axios library and simulate different API responses (successful, failed, 404, 500).


Now that you have all commonly used examples, it shouldn’t be too challenging to get started. However, if you’re wondering what are the common tests one should write for a component, here’s a cheat sheet

When testing a component, there are several types of tests you can write to ensure that it works as expected. Here are some common types of tests you should write for a component:

  1. Rendering test: This type of test checks if the component renders correctly. You can use functions from testing libraries like @testing-library/react to test if the component renders with the expected text, elements, and styles.
import React from 'react';
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
  it('renders with the expected text', () => {
    const { getByText } = render(<MyComponent text="Hello world" />);
    const textElement = getByText('Hello world');
    expect(textElement).toBeInTheDocument();
  });
});

In this example, we render the MyComponent component with a prop called text set to “Hello world”. We then use the getByText function from @testing-library/react to get the text element and check if it is in the document using the toBeInTheDocument function.

  1. Props test: This type of test checks if the component behaves correctly when receiving different props. You can use functions from testing libraries like @testing-library/react to test if the component renders correctly with different props.
import React from 'react';
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
  it('renders with the expected text', () => {
    const { getByText } = render(<MyComponent text="Hello world" />);
    const textElement = getByText('Hello world');
    expect(textElement).toBeInTheDocument();
  });

  it('renders with the default text if no text prop is provided', () => {
    const { getByText } = render(<MyComponent />);
    const textElement = getByText('Default text');
    expect(textElement).toBeInTheDocument();
  });
});

In this example, we add another test that checks if the MyComponent component renders with the default text if no text prop is provided.

  1. State test: This type of test checks if the component behaves correctly when its state changes. You can use functions from testing libraries like @testing-library/react to simulate user interactions and check if the component updates its state correctly.
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
  it('renders with the expected text', () => {
    const { getByText } = render(<MyComponent text="Hello world" />);
    const textElement = getByText('Hello world');
    expect(textElement).toBeInTheDocument();
  });

  it('updates the text when the button is clicked', () => {
    const { getByText } = render(<MyComponent text="Hello world" />);
    const buttonElement = getByText('Click me');
    fireEvent.click(buttonElement);
    const textElement = getByText('New text');
    expect(textElement).toBeInTheDocument();
  });
});

In this example, we add another test that checks if the MyComponent component updates its text when the button is clicked. We use the fireEvent.click function from @testing-library/react to simulate a user click on the button and then check if the text element is updated to “New text”.

  1. Lifecycle test: This type of test checks if the component behaves correctly during its lifecycle. You can use functions from testing libraries like jest to test if the component calls certain lifecycle methods at the right time.
import React from "react";
import { render } from "@testing-library/react";
import MyComponent from "./MyComponent";

describe("MyComponent", () => {
  it("renders with the expected text", () => {
    const { getByText } = render(<MyComponent text="Hello world" />);
    const textElement = getByText("Hello world");
    expect(textElement).toBeInTheDocument();
  });

  it("updates the text when the button is clicked", () => {
    const { getByText } = render(<MyComponent text="Hello world" />);
    const buttonElement = getByText("Click me");
    fireEvent.click(buttonElement);
    const textElement = getByText("New text");
    expect(textElement).toBeInTheDocument();
  });

  it("calls the componentDidMount method", () => {
    const componentDidMountSpy = jest.spyOn(
      MyComponent.prototype,
      "componentDidMount"
    );
    render(<MyComponent text="Hello world" />);
    expect(componentDidMountSpy).toHaveBeenCalled();
  });
});

In this example, we add another test that checks if the `MyComponent` component calls the `componentDidMount` method when it is mounted. We use the `jest.spyOn` function to spy on the `componentDidMount` method and then check if it has been called using the `toHaveBeenCalled` matcher. By writing these tests, you can ensure that your component works as expected and catches any bugs or unexpected behavior early on in the development process.

Another common test for a component is to test its interactions with external services or APIs. For example, if your component fetches data from a backend API, you can write a test to check if it correctly handles the response and displays the data.

Here’s an example:

import React from 'react';
import { render, waitFor } from '@testing-library/react';
import axios from 'axios';
import MyComponent from './MyComponent';

jest.mock('axios');

describe('MyComponent', () => {
  it('renders with data from the backend API', async () => {
    const responseData = {
      id: 1,
      name: 'John Doe',
      email: 'johndoe@example.com',
    };
    axios.get.mockResolvedValue({ data: responseData });
    const { getByText } = render(<MyComponent />);
    await waitFor(() => {
      const nameElement = getByText('Name: John Doe');
      const emailElement = getByText('Email: johndoe@example.com');
      expect(nameElement).toBeInTheDocument();
      expect(emailElement).toBeInTheDocument();
    });
  });
});

In this example, we use the jest.mock function to mock the axios library, which is used to make HTTP requests. We then use the mockResolvedValue method to set the response data for the mocked API request.

We then render the MyComponent component and use the waitFor function to wait for the API request to complete and for the component to render the data. We then use the getByText function to find elements in the component that contain the expected data and use the toBeInTheDocument matcher to check if they are present in the component.

By writing tests like these, you can ensure that your component works correctly with external services and APIs, and catches any errors or unexpected behavior early on in the development process.

Categories
Angular Front-end Development Performance React

Angular vs React: Which Framework Wins the Performance Race?

Reading Time: 4 minutes

Are you tired of waiting for your web application to load? Are you tired of watching your screen freeze up every time you try to interact with it? Change detection is the answer! But which framework has the better change detection mechanism, Angular or React? Let’s find out.

What is Change Detection?

Change detection is the process by which a framework or library detects changes to data and updates the user interface accordingly. In the context of web development, this typically refers to the process of updating the user interface in response to changes in the application state or user input.

Angular Change Detection

Angular uses a change detection mechanism that works by traversing the component tree, starting from the root component, and checking each component and its child components for changes.

Angular uses a Zone.js library to implement change detection. Zones provide a way to intercept and track asynchronous operations, including those triggered by browser events, and trigger change detection as needed. Angular’s change detection algorithm works by traversing the component tree, starting from the root component, and checking each component and its child components for changes.

By default, Angular’s change detection runs every time an event occurs, which can result in performance issues in large and complex applications. To optimize performance, developers can use the on-push change detection strategy, which runs change detection only when the input properties of a component change or when an event is triggered by the component itself.

To use the on-push change detection strategy, you need to change the change detection mode of a component from default to on-push. This strategy requires careful management of the component state, and developers must ensure that all input properties of a component are immutable and that any changes to the state are made using pure functions. This can be done in the component decorator by adding the changeDetection property with the value of ChangeDetectionStrategy.OnPush, like this:

import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-todo-component',
  template: `
    <h1>{{ title }}</h1>
    <button (click)="updateTitle()">Update Title</button>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ToDoComponent {
  title = 'My TO-DO List';

  updateTitle() {
    this.title = 'My TO-DO List for April 11, 2023';
  }
}

In this example, the ToDoComponent is using the on-push strategy, which means that it will only run change detection when the input properties of the component change or when an event is triggered by the component itself, such as the button click event.

React Change Detection

React uses a virtual DOM (VDOM) to implement change detection. When a component’s state or props change, React updates the VDOM and then compares the updated VDOM to the previous VDOM to determine which parts of the UI need to be updated.

React’s VDOM allows it to minimize the number of actual DOM updates required, which can result in better performance compared to Angular. However, the VDOM approach can also introduce overhead, particularly in large and complex applications.

To optimize performance in React, developers can use memoization to prevent unnecessary re-rendering of components. Memoization is a technique that involves caching the results of expensive computations so that they can be reused later without recomputing them. By memoizing expensive computations, developers can reduce the number of times that components need to be re-rendered, improving overall performance.

Here’s an example of memoizing a value in React using the useMemo hook:

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

function ExpensiveCalculation() {
  console.log('Performing expensive calculation...');
  // ... expensive computation here ...
  return calculatedValue;
}

function Example() {
  const [value, setValue] = useState(0);

  const calculatedValue = useMemo(() => ExpensiveCalculation(), [value]);

  function handleClick() {
    setValue(value + 1);
  }

  return (
    <div>
      <button onClick={handleClick}>Increment Value</button>
      <div>Calculated Value: {calculatedValue}</div>
    </div>
  );
}

In this example, ExpensiveCalculation is a function that performs a computationally expensive calculation and returns a value. In the Example component, the useMemo hook is used to memoize the value returned by ExpensiveCalculation. The useMemo hook takes two arguments: a function that performs the expensive calculation and an array of dependencies that determine when the calculation should be re-executed. In this case, the dependency is value, which is updated whenever the user clicks the button.

When the user clicks the button, the value state is updated, triggering a re-render of the Example component. However, because the value returned by ExpensiveCalculation is memoized using useMemo, the calculation is only re-executed when value changes. This can significantly improve the performance of the application by reducing the number of unnecessary calculations.

Comparing Angular and React Change Detection

So, which change detection mechanism is better, Angular or React? The answer is, it depends on your application’s requirements. Angular’s change detection is more straightforward and easier to manage but can be less performant in large and complex applications. React’s VDOM approach is more complex but can be more performant by minimizing the number of actual DOM updates required.

To achieve high performance in both Angular and React, developers must carefully manage component state and use techniques such as memoization to optimize rendering. Developers should also be aware of the trade-offs between different change detection approaches and choose the one that best suits their application’s requirements.

To sum it up, Change detection is a critical part of any web application that involves dynamic updates to the user interface. Angular and React provide different mechanisms for implementing change detection, and each has its strengths and weaknesses. By understanding these differences and using best practices for managing component state and optimizing rendering, developers can achieve high performance in both frameworks. So, choose your framework wisely, and happy coding!