How To Optimize AG Grid Efficiency With React – DZone – Uplaza

AG Grid is a feature-rich JavaScript library primarily used to construct strong knowledge tables in net purposes. It’s utilized by nearly 90% of Fortune 500 corporations and it’s particularly helpful in Enterprise Intelligence (BI) purposes and FinTech purposes.

React is the market chief of JavaScript libraries to construct enterprise net and cell purposes. It’s broadly adopted by main corporations and boasts a big group.

On this article, we’ll arrange a React net software and use AG Grid to construct a performant knowledge desk. All of the code on this article is accessible at this GitHub hyperlink. 

Stipulations

  • Node.js and npm are put in in your system.
  • Information of JavaScript and React.

Arrange a New React Software

  • Confirm that  NodeJS and NPM are put in. Instructions to examine: node -v and npm -v
  • We’ll use “create react app” to provoke a brand new React software, let’s set up it globally on the machine utilizing npm set up -g create-react-app
  • Create a brand new React software utilizing npx create-react-app AGGridReact
  • Look ahead to the app to be totally created after which go to the newly created app’s folder utilizing cd AGGridReact
  • Begin the appliance utilizing npm begin. Quickly it is possible for you to to entry this react app on localhost port 3000 utilizing the URL
  • Now we’re able to make modifications to our React app. You should use the code editor of your alternative, I’ve used Visible Studio Code.

Integrating AG Grid Into Our React App

AG Grid is available in two flavors, group model and enterprise model. We’ll use the group model to not incur any licensing charge. The enterprise model is most well-liked in giant companies as a result of set of extra options it gives.

  • Set up the AG Grid group model with React help utilizing npm set up ag-grid-react
  • Let’s create two folders beneath the src folder in our undertaking: elements and providers.
  • Let’s create a service beneath the providers folder. This service could have the job of speaking to the backend and fetching knowledge. For simplicity functions we is not going to be doing precise API calls, as a substitute, we could have a JSON file with all pattern knowledge.  
  • Let’s create movie-data.json file and add content material to it from right here.
  • Add movie-service.js to the providers folder. Our service could have two strategies and one exported fixed. Quickly, all of those will make sense. Beneath is the reference code for this file.
import motion pictures from './movie-data.json';

const DEFAULT_PAGE_SIZE = 5;

const countOfMovies = async() => {
    return motion pictures.motion pictures.size;
};

const fetchMovies = async() => {
    return motion pictures.motion pictures;
};

export { DEFAULT_PAGE_SIZE, countOfMovies, fetchMovies };

At this level let’s create our React element which can maintain AG Grid Desk. Add AGGridTable.js file beneath the elements folder beneath the src listing.

Let’s import React and AG Grid in our element and lay down primary element export

import React, { useState, useEffect } from 'react';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/types/ag-grid.css';
import 'ag-grid-community/types/ag-theme-quartz.css';
export const AgGridTable = () => {}

We’re going to use the AGGridReactelement to render our desk, this element wants two primary issues:

  • Columns we wish to show in our desk.
  • Rows we wish to show in our desk.

Now we have to go a parameter named columnDefs to our AGGridReact to inform it how we wish our columns to be arrange. When you take a look at our film knowledge in movie-data.json file now we have columns movieID, movieName and releaseYear. Let’s map these to our column definitions parameters. We will obtain it utilizing the under strains of code.

    const columnDefs = [
        { field: 'movieId', headerName: "Movie ID", minWidth: 100 },
        { field: 'movieName', headerName: "Movie Name", flex: 1 },
        { field: 'releaseYear', headerName: "Release Year", flex: 1 }
    ];

We have to fetch precise film knowledge, and we’re going to leverage the fetchMovies operate from our film service. Additionally, we might wish to load it on web page load. This may be achieved utilizing the useEffect hook of React by passing an empty dependency array.

    useEffect(() => {
        const fetchCount = async () => {
            const totalCount = await countOfMovies();
            setTotalRecords(totalCount);
        }
        fetchCount();
    }, []);

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        setIsLoading(true);
        strive {
            const response = await fetchMovies();
            setMovieData(response);
        } catch (error) {
            console.error(error);
        } lastly {
            setIsLoading(false);
        }
    };

Let’s add some good loading indicator variables to point to our customers one thing is getting processed. 

 const [isLoading, setIsLoading] = useState(false);

Placing every little thing collectively we get our element as under.

import React, { useState, useEffect } from 'react';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/types/ag-grid.css';
import 'ag-grid-community/types/ag-theme-quartz.css';

import { countOfMovies, fetchMovies } from '../providers/movie-service';

export const AgGridTable = () => {
    const [movieData, setMovieData] = useState([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [isLoading, setIsLoading] = useState(false);

    const columnDefs = [
        { field: 'movieId', headerName: "Movie ID", minWidth: 100 },
        { field: 'movieName', headerName: "Movie Name", flex: 1 },
        { field: 'releaseYear', headerName: "Release Year", flex: 1 }
    ];

    useEffect(() => {
        const fetchCount = async () => {
            const totalCount = await countOfMovies();
            setTotalRecords(totalCount);
        }
        fetchCount();
    }, []);

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        setIsLoading(true);
        strive {
            const response = await fetchMovies();
            setMovieData(response);
        } catch (error) {
            console.error(error);
        } lastly {
            setIsLoading(false);
        }
    };

    return (
        
            {isLoading && 

Loading...

} > ) }

Let’s replace our app.js to incorporate our newly constructed element and carry out cleanup to take away primary create React app-generated code. Beneath is the up to date code for app.js:

import './App.css';
import { AgGridTable } from './elements/AgGridTable';

operate App() {
  return (
    
  );
}

export default App;

Our desk ought to load on the UI now.

Enhancing Efficiency With Pagination

Now we have been rendering all of the rows within the desk in a single go until now. This method doesn’t scale in the actual world. Think about we had 10000 rows as a substitute of simply 100, our web page could be very gradual and UI efficiency would take an enormous hit.

We will simply improve this by paginating by way of our knowledge. In easier phrases, pagination means breaking our knowledge right into a set of x objects and displaying one set merchandise at a time.

Some key advantages of including paginations are:

  • Lowered DOM Measurement leading to Optimized Reminiscence Utilization
  • Improved Rendering Pace
  • Enhanced Scrolling Efficiency
  • Quicker Updates

Let’s add extra parameters to the AGGridReact setup to allow pagination.

  • pagination = true to tells AG Grid we wish to paginate
  • paginationPageSize tells AG Grid what’s the default variety of objects to be displayed on the web page initially.
  • We’d be passing an array to the paginationPageSizeSelector parameter. It should outline totally different web page sizes we enable our customers to select from.
  • totalRows tells AG Grid what number of information in whole there are, which, in flip, helps depend the variety of pages in our desk.
  • To have the best worth for the entire above parameters we have to replace our code to fetch the entire row depend and outline the web page dimension selector array. 
import React, { useState, useEffect, useMemo } from 'react';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/types/ag-grid.css';
import 'ag-grid-community/types/ag-theme-quartz.css';

import { DEFAULT_PAGE_SIZE, countOfMovies, fetchMovies } from '../providers/movie-service';

export const AgGridTable = () => {
    const [movieData, setMovieData] = useState([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [isLoading, setIsLoading] = useState(false);

    const columnDefs = [
        { field: 'movieId', headerName: "Movie ID", minWidth: 100 },
        { field: 'movieName', headerName: "Movie Name", flex: 1 },
        { field: 'releaseYear', headerName: "Release Year", flex: 1 }
    ];

    useEffect(() => {
        const fetchCount = async () => {
            const totalCount = await countOfMovies();
            setTotalRecords(totalCount);
        }
        fetchCount();
    }, []);

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        setIsLoading(true);
        strive {
            const response = await fetchMovies();
            setMovieData(response);
        } catch (error) {
            console.error(error);
        } lastly {
            setIsLoading(false);
        }
    };

    const paginationPageSizeSelector = useMemo(() => {
        return [5, 10, 20];
    }, []);

    return (
        
            {isLoading && 

Loading...

} > ) }

With this code, we could have good pagination constructed into it with default web page dimension.

Conclusion

AG Grid integration with React is simple to arrange, and we will enhance the efficiency with methods similar to paginations. There are different methods to lazy load rows in AG Grid past pagination. Going by way of the AG Grid documentation ought to enable you to get accustomed to different strategies. Blissful coding!

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version