Thinking in React Hooks: Building an App With Embedded Analytics
See how to use Hooks in React.
Join the DZone community and get the full member experience.
Join For FreeYou may have noticed that React Hooks, introduced in the React’s 16.8.0 release, have been received by the web dev community very diversely. Some warmly embraced this new way to reuse stateful logic between components, while some strongly criticized it. One thing can be said for sure — React Hooks are an incredibly hot topic now. This is confirmed by the number of articles, tutorials, video courses, and project samples on the subject.
My goal is to briefly introduce to you this powerful concept (if you are not familiar with it yet) and show how it can be applied to building a simple analytical app. Note that we’ll focus more on getting a hands-on experience rather than on debating on the pros and cons of using Hooks.
I do hope this article will satisfy your intellectual curiosity in full and inspire to create your own analytical application that assists in making important business decisions.
You may also like: Everything React: Tutorials for Beginners and Experts Alike.
Why React Hooks
The central idea behind React Hooks is that you can use React’s features (like states and effects) from functions, without writing classes. Hooks are meant to help you arrange logic inside a component into separate pieces. Ergo, they present a powerful mechanism for code reuse.
Plus, there's no need to worry — you don’t have to rewrite your code from scratch and add hooks everywhere. React Hooks are an experimental and backward-compatible feature that are currently being adopted among web developers.
☝️ Now that we figured out what React Hooks are all about, let’s go ahead and try building an analytical app with React Hooks.
As a data analysis tool, I’ve chosen Flexmonster Pivot Table & Charts, since it provides a ready-to-use React wrapper based on React Hooks.
To make the process more engaging, we’ll explore the data set from Kaggle, namely Spanish High-Speed Rail tickets pricing - Renfe. To be precise, we’ll aggregate, filter, and sort the data in the pivot table. Afterward, we’ll visualize it with pivot charts. This kind of exploration will help us to capture trends in the data and get a basic understanding of working with a web pivot table. And we’ll do it all in our React app!
Results
After tutorial completion, we’ll end up with a dynamic web-based dashboard displaying metrics inside your React app:
Creating a React App and Adding Dependencies
The first step is completely straightforward. All you need to do is to download or clone the project from GitHub. At this point, you should select between ES6 or TypeScript versions of the project. Next, run npm install
to download its dependencies.
Alternatively, you can build a single-page app from scratch using the create-react-app
environment and go the full way of integrating it with Flexmonster. Here is a tutorial on how to add the component to the existing project in a few steps.
If you prefer the first variant, let’s take a closer look at the structure of the sample project and a couple of JS components from the src folder that we'll be using.
- App.js is the main JavaScript component that is responsible for setting routes of other components and running your app.
- PivotTableHooks.js renders the instance of a pivot table using the functional approach with hooks.
I'd like to draw your attention to how easy it is to hook React features of Flexmonster into your functional component.
It's as simple as changing the import statement from
import * as FlexmonsterReact from 'react-flexmonster';
to
import * as FlexmonsterReact from 'react-flexmonster/hooks';
Afterward, you can use the pivot table within a function. You can also do this inside a class component, which is PivotTable.js in our sample.
In my mind, such a seamless approach corresponds to the very nature of hooks as a concept and speeds up the development process and helps to keep the code clear.
Note that PivotTable.js and PivotTableHooks.js can be used interchangeably, depending on the logic you like better — a class-based or with hooks.
Empowering the App With a Data Visualization Solution
Now, it’s time to figure out how to work with Flexmonster Pivot. First, we need to configure a report.
Flexmonster’s report has a clear JSON structure. It incorporates information about a data source, a slice (a subset of data that is currently displayed on the grid), visual and functional options, formatting, etc.
Open the PivotTableHooks.js file and define a variable that contains our JSON data:
const data = [
{
"insert_date": "2019-04-11 21:49:46",
"origin": "MADRID",
"destination": "BARCELONA",
"start_date": "2019-04-18 05:50:00",
"end_date": "2019-04-18 08:55:00",
"train_type": "AVE",
"price": 68.95,
"train_class": "Preferente",
"fare": "Promo"
},
{
"insert_date": "2019-04-11 21:49:46",
"origin": "MADRID",
"destination": "BARCELONA",
"start_date": "2019-04-18 06:30:00",
"end_date": "2019-04-18 09:20:00",
"train_type": "AVE",
"price": 75.4,
"train_class": "Turista",
"fare": "Promo"
},
// …
]
Next, create a variable that holds the report itself:
const report = {
dataSource: {
data: data
},
"slice": {
"reportFilters": [{
"uniqueName": "train_class"
},
{
"uniqueName": "train_type"
}
],
"rows": [{
"uniqueName": "origin"
}],
"columns": [{
"uniqueName": "destination"
},
{
"uniqueName": "fare"
},
{
"uniqueName": "[Measures]"
}
],
"measures": [{
"uniqueName": "price",
"aggregation": "average"
}],
"expands": {
"columns": [{
"tuple": [
"destination.[madrid]"
]
}]
}
}
};
As an alternative, we can simply pass a string with the report’s URL:
report = "URL-to-report"
Set the report in the pivot table:
<FlexmonsterReact.Pivot ref={ref} toolbar={true} width="100%" report={report} reportcomplete={onReportComplete}/>
To add charts, we need to create a separate instance of Flexmonster and make it display charts with our data. We can do it by creating one more report and setting options.
const report_charts = {
dataSource: {
data: data
},
"slice": {
"reportFilters": [{
"uniqueName": "train_class"
},
{
"uniqueName": "destination"
},
{
"uniqueName": "fare"
}
],
"rows": [{
"uniqueName": "train_type"
}],
"columns": [{
"uniqueName": "[Measures]"
}],
"measures": [{
"uniqueName": "price",
"aggregation": "average",
"format": "currency"
}]
},
"options": {
"viewType": "charts",
"chart": {
"type": "pie"
}
},
"formats": [{
"name": "currency",
"thousandsSeparator": ",",
"decimalPlaces": 1,
"currencySymbol": "€"
}]
};
<FlexmonsterReact.Pivot ref={ref_charts} toolbar={true} width="100%" report={report_charts}/>
After, run `npm start` and open `http://localhost:3000/hooks` in your browser.
Now the pivot table component is rendered and filled with the predefined data.
It’s worth noting that the majority of configurations we apply in code are accessible also via the UI. For example, we can highlight the cells we are most interested in:
Or change the slice with the drag-and-drop feature:
And here’s what we’ve got:
See the Pen Analysis of Spanish High Speed Rail tickets pricing with Flexmonster by Flexmonster (@flexmonster) on CodePen.
A React Hooks application empowered with a custom reporting solution that is ready to be used in any app for tackling all kinds of data analysis challenges.
I encourage you to take some time experimenting with this embedded analytics solution to explore its full potential and discover new insights into the data.
You can also see the React project on GitHub.
Any of your feedback or questions would be so much appreciated!
Resources
If you want to develop an in-depth intuition for React Hooks, you can take advantage of an official introduction to React Hooks and listen to these three great talks from React Conf 2018. If you are an experienced React programmer, you may also like the guide that covers Hooks in a more advanced manner.
Also, it’s worth looking at this awesome curated list about React Hooks.
To explore the basic features of Flexmonster Pivot Table & Charts as well as its customization and integration options, go through live demos and check the list of available tutorials.
Further Reading
Opinions expressed by DZone contributors are their own.
Trending
-
How AI Will Change Agile Project Management
-
Performance Comparison — Thread Pool vs. Virtual Threads (Project Loom) In Spring Boot Applications
-
A Comprehensive Guide To Testing and Debugging AWS Lambda Functions
-
How To Use an Automatic Sequence Diagram Generator
Comments