React.js: Using the "useTransition()" hook to draw the self-updated chart
The React.js library is improvising with its power and provides several features to design feature rich composable applications. The hooks are the most important features of this library. These hooks are used for state updates, side-effect handling, context data sharing, etc. In React 18 the useTransition() hook is introduced.
The useTransition() Hook
The useTransition() hook is a React hook that helps to handle state updates in a non-blocking manner. This is particularly useful when dealing with asynchronous operations like API calls or expensive computations. This hook helps to prevent the UI freezes. We use this hook to update the state without bocking the UI.
The useTransition hook does not take any parameters. The useTransition returns an array with following two items:
- The isPending flag that specifies whether there is a pending Transition
- The startTransition function, this help to mark a state update as a Transition. The startTransition does not return anything.
using Microsoft.AspNetCore.Http.Json; var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.Configure<JsonOptions>(options => { options.SerializerOptions.PropertyNamingPolicy = null; }); builder.Services.AddCors(options => { options.AddPolicy("cors", policy => { policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseCors("cors"); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; app.MapGet("/wf", () => { var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast ( DateOnly.FromDateTime(DateTime.Now.AddDays(index)), Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); return forecast; }) .WithName("GetWeatherForecast") .WithOpenApi(); app.Run(); internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); }
import React, { useEffect, useState, useTransition } from 'react'; import { Line, Bar } from 'react-chartjs-2'; import axios from 'axios'; /* Import elements */ import { Chart, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, PointElement,LineElement,LineController } from 'chart.js'; Chart.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, PointElement,LineElement,LineController ); const WeatherChartComponent = () => { /* Define the initial data from the chart */ const [chartData, setData] = useState({ labels: [], datasets: [ { label: 'The Weather Forecast Chart', data: [], /* The Data that will be used to draw the chart */ borderColor: 'blue', borderWidth: 2, fill: false, }, ], }); const [isPending, startTransition] = useTransition(); useEffect(() => { const fetchChartData = async () => { try { const response = await axios.get('http://localhost:5000/wf'); const data = response.data; startTransition(() => { setData((prevData) => ({ ...prevData, labels: data.map((item:any) => item.Summary), datasets: [ { ...prevData.datasets[0], data: data.map((item:any) => item.TemperatureF), }, ], })); }); } catch (error) { console.error('Error fetching data', error); } }; fetchChartData(); const interval = setInterval(fetchChartData, 3000); // Fetch data every 3 seconds return () => { clearInterval(interval); /* Dispose the Chart */ Object.keys(Chart.instances).forEach((key) => { const instance = Chart.instances[key]; if (instance) { instance.destroy(); } }); } }, [startTransition]); return ( <div className="container"> <h2>Dynamic Chart</h2> {isPending && <p>Loading...</p>} <Line data={chartData} /> <br/> {/* <Bar data={chartData} /> */} </div> ); }; export default WeatherChartComponent;