Categories
JavaScript APIs

Using the React-Redux Hooks API to Manipulate Store State

With Redux, we can use it to store data in a central location in our JavaScript app. It can work alone and it’s also a popular state management solution for React apps when combined with React-Redux.

In this article, we’ll look at how to use the useDispatch and useStore hooks in the React-Redux hooks API, and also look at performance and stale state issues.

useDispatch

We can use the useDispatch hook to get the dispatch function to dispatch actions to the store.

For example, we use useDispatch as follows:

import React from "react";
import ReactDOM from "react-dom";
import { Provider, useSelector, useDispatch } from "react-redux";
import { createStore } from "redux";

function count(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}

const store = createStore(count);

function App() {
  const count = useSelector(state => state);
  const dispatch = useDispatch();
  return (
    <div className="App">
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
      <p>{count}</p>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

In the code above, we called useDispatch in App to get the dispatch function so that we can dispatch actions from the store.

Then we create functions that call dispatch to pass into the onClick prop.

useStore

We can use the useStore hook to get the reference to the Redux store. It’s the same one that we passed into the Provider component.

This shouldn’t be used frequently since we aren’t supposed to access the store directly within a React app since it doesn’t update according to the React update cycle.

Stale Props and “Zombie Children”

Stale props mean that a selector function relies on a component’s props to extract data, a parent component would re-render and pass down new props as a result of an action, but the component’s selector functions execute before the component has a chance to re-render with those new props.

This causes outdated data to be displayed. in the child component or an error being thrown.

“Zombie child” refers to the cases where multiple nested connected components are mounted ina first pass, causing a child component to subscribe to the store before its parent. Then an action is dispatched that deletes data from the store. The parent component would stop rendering the child as a result.

Because the child subscribed to the store first, its subscription runs before the parent stops render. When it reads a value based on props, the data no longer exists. Then an error may be thrown when the extraction logic doesn’t check for the case of the missing data.

Therefore, we should rely on props in our selector function for extracting data.

connect adds the necessary subscription to the context provider and delays evaluating child subscriptions until the connected component has re-rendered. Putting a connected component in the component tree just above the component using useSelector will prevent the issues above.

Performance

useSelector will do a reference equality comparison of the selected value when running the selector function after an action is dispatched.

It’ll only re-render if the previous state is different from the current state. connect and useSelector doesn’t prevent the component from re-rendering because of its parent re-rendering.

To stop parent re-rendering from re-rendering the child, we can use memoization to prevent that.

For example, we can write the following:

import React from "react";
import ReactDOM from "react-dom";
import { Provider, useSelector, useDispatch } from "react-redux";
import { createStore } from "redux";

function count(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}

const store = createStore(count);

function App() {
  const count = useSelector(state => state);
  const dispatch = useDispatch();
  return (
    <div className="App">
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
      <p>{count}</p>
    </div>
  );
}

App = React.memo(App);

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

In the code above, we added the React.memo call as follows:

App = React.memo(App);

to cache existing results and preventing re-render if the state remains the same.

Conclusion

We can use the useDispatch hook to get the dispatch function to update the store’s state.

There’s also a useStore hook to get a reference of the Redux store in our React components.

However, we shouldn’t access the store directly with useStore since we’re supposed to use useSelector to get the latest state from the store and use useDispatch to dispatch actions.

Also, we have to be aware of stale props from parent components and child components that have been removed because of state changes throwing errors and displaying incorrect data.

We should also memoize the state of components to cache them so that they don’t have to re-render when nothing changed.

Categories
JavaScript APIs

Introducing the JavaScriptWeb Animations API

The JavaScript Web Animations API is a new API that lets us create animations with JavaScript by manipulating the elements that we want to animate.

In this article, we’ll look at how to create simple animations with the API.

Basic Usage

The way we create the animation is similar to how we do it with CSS. We specify how the element animates by specifying how we transform the element in keyframes. The only difference is that we do it with JavaScript instead of CSS.

To animate an element, we call the animate method on the element with 2 arguments. The first argument is an array with the keyframe for each entry. Each keyframe object has the styles to apply when the keyframe is displayed.

The second object is the timing object, which has the duration and iterations properties. duration is the number of milliseconds to animate the element. The iteration is the number of iterations to run the animation for. It can be a positive number of Infinity .

For instance, we can write the following HTML and JavaScript to animate an object:

HTML:

<img src='https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg' width=100 height=100>

JavaScript:

const action = [{
    transform: 'rotate(0) translate3D(-50%, -50%, 0)',
    color: '#000'
  },
  {
    color: '#431236',
    offset: 0.3
  },
  {
    transform: 'rotate(360deg) translate3D(-50%, -50%, 0)',
    color: '#000'
  }
];

const timing = {
  duration: 3000,
  iterations: Infinity
}

document.querySelector("img").animate(
  action,
  timing
)

The action array has the keyframe styles and the timing object has the duration and the number of iterations of the animation to run.

Then we should see an image that rotates forever.

Controlling playback with play(), pause(), reverse(), and playbackRate

The animate method returns an object with the play , pause and reverse methods. playbackRate is a numerical property that can be set by us. A negative playback rate means the animation plays in reverse.

For instance, we can add buttons to call these methods as follows. First, we add the following HTML code to add buttons for the playing, pausing, and reversing, and also a range slider for changing the playback rate:

<button id='play'>Play</button>
<button id='pause'>Pause</button>
<button id='reverse'>Reverse</button>
<input type='range' min='-2' max='2'>

<img src='https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg' width=100 height=100>

Then we add some CSS to move the image:

img {
  position: relative;
  top: 100px;
  left: 100px;
}

Finally, we add the JavaScript for the animation and event handler for the buttons and input that call the methods and set the playbackRate property as follows:

const action = [{
    transform: 'rotate(0) translate3D(-50%, -50%, 0)',
    color: '#000'
  },
  {
    color: '#431236',
    offset: 0.3
  },
  {
    transform: 'rotate(360deg) translate3D(-50%, -50%, 0)',
    color: '#000'
  }
];

const timing = {
  duration: 3000,
  iterations: Infinity
}

const animation = document.querySelector("img").animate(
  action,
  timing
)

const play = document.getElementById('play');
const pause = document.getElementById('pause');
const reverse = document.getElementById('reverse');
const range = document.querySelector('input');

play.onclick = () => animation.play();
pause.onclick = () => animation.pause();
reverse.onclick = () => animation.reverse();
range.onchange = () => {
  const val = range.value;
  animation.playbackRate = +val;
}

In the code above, we added the buttons. Then in the JavaScript, we have:

const play = document.getElementById('play');
const pause = document.getElementById('pause');
const reverse = document.getElementById('reverse');
const range = document.querySelector('input');

play.onclick = () => animation.play();
pause.onclick = () => animation.pause();
reverse.onclick = () => animation.reverse();
range.onchange = () => {
  const val = range.value;
  animation.playbackRate = +val;
}

to call the methods and set the properties on animation , which is assigned to the animation object that’s returned by animate .

Then we can do whatever action is indicated by the method’s names and also set the playback rate when we move the slider.

Getting Information Out of Animations

We can also get more information out of the animation object, like the duration and the current time of the animation.

We can get all that information from the animation object in the code above. In Chrome, we have the startTime and currentTime to get the start time and current time of the animation respectively.

It also has the playState and playbackRate . The properties of the animation object may differ between browsers.

Conclusion

We can create simple animations with the Web Animations API. It’s a simple API that lets us define keyframes for animation as we do with CSS animations.

The only difference is that we can do more things like changing the playback rate, and controlling the playback of the animation with play, pause, and reverse.

Categories
JavaScript APIs

Side Projects That We Can Create With Free APIs

In the software development world, practice makes perfect. Therefore, we should find as many ways to practice programming as possible. With free public APIs, we can practice programming by creating apps that use those APIs.

In this article, we’ll look at some practice project ideas that can use some of those APIs.

Email Address Validator

We can use the MailboxValidator API to validate the email address so that we can make sure that are sending our email to a valid email address.

It’s great for marketers and salespeople to clean up their email lists so that they aren’t sending stuff to defunct or invalid email addresses.

The API can be accessed by signing up for an API key.

Email Automation App

We can write our own app to send emails by using the Mailgun API. It lets us send emails in batches to the email address of our choice.

Just make sure that we use it responsibly so that we aren’t sending our spam.

It has SDKs for many platforms like Python, Ruby, Perl, Java, Kotlin, Go, C#, Go, Node.js, and Luvit.

It can also be called from cURL directly.

It has a free tier so we can use it for practice and if we like it and want to use it for more things, we can pay for more access to the API.

The free tier according to this webpage has the following:

  • send 5000 messages a month
  • send 300 messages a day from the sandbox domain
  • data retention for logs for a day
  • no custom domains
  • send up to 5 authorized recipients max

That’s definitely good enough if we’re only creating a practice app with it.

It also has APIs for email validation and API for sending more than a million emails a day.

Also, it has a deliverable service to improve deliverability.

Google Calendar App

With the Google Calendar API, we can create our programs to customize bring Google Calendar functionality to our own app.

We can use it to display, create and modify Google Calendar events.

Also, we can get push notifications, batch requests, and create and get reminders and notifications.

File Sharing App

We can use the Box, Dropbox, Google Drive, or OneDrive APIs to upload and download files from those provides automatically.

They all use OAuth authentication, so we can practice using that. With these APIs, we can automate the upload and download of data the way we please.

Also, we can automatically share data with other people of our choice.

With the Pastebin API, we can upload text to Pastebin and share it with other people. All it takes is registering for a free API key then we’re set.

Cryptocurrency Apps

There’re lots of cryptocurrency APIs to get various kinds of cryptocurrency information like exchange rates and prices of various cryptocurrencies.

Also, there are many APIs that are used for trading cryptocurrencies automatically.

This can be our opportunity to beat the market by using programs to help us trade faster than other people that don’t know how to program.

For instance, to get cryptocurrency information, there are the Coinbase, CoinAPI, and CoinDesk APIs. They all require an API key to get access to them.

If we want to write programs to trade cryptocurrency, we can use the Bitfinex, Bitmex, and Bittrex APIs. They all require an API key to get access to them.

Real Currency Apps

There are also many APIs for getting real currency data.

We can get exchange rates from the Exchangeratesapi.io, ExchangeRate-API, Czech National Bank, Fixer.io and Frankfurter APIs.

Most of them don’t need any authentication to get access to their data except the Frankfurter API, which requires an API key.

Photo by Pepi Stojanovski on Unsplash

Data Validation Apps

We can use data validation APIs to validate various kinds of data.

For instance, we can send email addresses, phone numbers, VAT numbers, and domain names to the Cloudmersive Validate API to validate them.

All we need is an API key to gain access to the API.

To check the language that a given piece of text is written in, we can use the languagelayer API to check what language it’s written.

It requires no authentication for access.

Conclusion

We can write practice apps to validate various kinds of data like email address and the language that something is written in with various data validation APIs.

Also, we can use free APIs to automate tasks like sending emails and updating our calendars.

Of course, the free version of those APIs aren’t going to very useful compared to the paid counterparts, but it’s still plenty good for using them for practice apps.

Categories
JavaScript APIs

Measuring Navigation Time with the JavaScript Navigation API

To measure navigation events like page load and going to different pages, we can use the Navigation Timing API.

In this article, we’ll take a look at how to use it in various scenarios.

Navigation Timing API

We can use the Navigation Timing API to collect performance data on the client which can then be transmitted to a server. The API also lets us measure data that was previously difficult to obtain, like the amount of time needed to unload the previous page, the time it takes to look up domains, total time pent running window’s load handler, etc.

All timestamps returned are measured in milliseconds. All properties are read-only.

The main interface for measure navigation performance is the PerformanceNavigationTiming interface.

A simple example to measure page load time would be the following:

const perfEntries = performance.getEntriesByType("navigation");
const [p] = perfEntries;
const pageLoadTime = `p.loadEventEnd - p.loadEventStart;`
console.log(pageLoadTime)

The code above measures the time between the loadEventStart event and loadEventEnd event is triggered.

We can also use it to measure how long it takes the DOM of a document to load as follows:

const perfEntries = performance.getEntriesByType("navigation");
const [p] = perfEntries;
const domLoadTime = p.domContentLoadedEventEnd - p.domContentLoadedEventStart;
console.log(domLoadTime)

In the code above, we used the domContentLoadedEventEnd and domContentLoadedEventStart properties to get the timing of the when the DOM finished loading and when the DOM started loading with those 2 properties respectively.

We can also use the domComplete to get when the DOM finished loading and when the page is interaction with the interactive properties of a performance entry.

We can write the following:

const perfEntries = performance.getEntriesByType("navigation");
const [p] = perfEntries;
console.log(p.domComplete);

Likewise, we can do something similar to measuring unloading time:

const perfEntries = performance.getEntriesByType("navigation");
const [p] = perfEntries;
const domLoadTime = p.unloadEventEnd - p.unloadEventStart;
console.log(domLoadTime)

Other Properties

We can get the number of redirects since the last non-redirect navigation under the current browsing context with the redirectCount read-only property.

To use it, we can write the following:

const perfEntries = performance.getEntriesByType("navigation");
const [p] = perfEntries;
console.log(p.redirectCount);

The type property will get us the navigation type. The possible values of this property are 'navigate', 'reload', 'back_forward', or 'prerender'.

We can get the type as follows:

const perfEntries = performance.getEntriesByType("navigation");
const [p] = perfEntries;
console.log(p.type);

Methods

We can serialize a PerformanceNavigationTiming object with the toJSON method.

To use it, we can write:

const perfEntries = performance.getEntriesByType("navigation");
const [p] = perfEntries;
console.log(p.toJSON());

Then we get something like the following from the console.log:

{
  "name": "https://fiddle.jshell.net/_display/",
  "entryType": "navigation",
  "startTime": 0,
  "duration": 0,
  "initiatorType": "navigation",
  "nextHopProtocol": "h2",
  "workerStart": 0,
  "redirectStart": 0,
  "redirectEnd": 0,
  "fetchStart": 0.31999999191612005,
  "domainLookupStart": 0.31999999191612005,
  "domainLookupEnd": 0.31999999191612005,
  "connectStart": 0.31999999191612005,
  "connectEnd": 0.31999999191612005,
  "secureConnectionStart": 0.31999999191612005,
  "requestStart": 2.195000008214265,
  "responseStart": 89.26000000792556,
  "responseEnd": 90.5849999981001,
  "transferSize": 1435,
  "encodedBodySize": 693,
  "decodedBodySize": 1356,
  "serverTiming": [],
  "unloadEventStart": 95.75999999651685,
  "unloadEventEnd": 95.75999999651685,
  "domInteractive": 116.96000001393259,
  "domContentLoadedEventStart": 116.97000000276603,
  "domContentLoadedEventEnd": 117.20500001683831,
  "domComplete": 118.64500000956468,
  "loadEventStart": 118.68000001413748,
  "loadEventEnd": 0,
  "type": "navigate",
  "redirectCount": 0
}

Conclusion

The PerformanceNavigationTiming interface is very handy for measure page navigation and loading times.

It’s information that’s hard to get any other way.

The interface provides us with various read-only properties that give us the timing of when various page load and navigation-related events occurred. All times are measured in milliseconds.

Categories
JavaScript APIs

Measuring JavaScript App Performance with the Performance API

With the JavaScript Performance API, we have an easy way to measure the performance of a front-end JavaScript apps.

In this article, we’ll look at how to use it to measure our app’s performance.

Performance

We can measure the performance of an app with a few methods. The Performance API provides a precise and consistent definition of time. The API will gives us with a high precision timestamp to mark the time when a piece of code starts running and finishes.

The timestamp is in milliseconds and it should be accurate to 5 microseconds. The browser can represent the value as time in milliseconds accurate to a millisecond if there’re hardware or software constraints that make our browser unable to provide value with the higher accuracy.

We can use it as in the following example:

const startTime = performance.now();
for (let i = 0; i <= 10000; i++) {
  console.log(i);
}
const endTime = performance.now();
console.log(endTime - startTime)

In the code above, we used the performance object to mark the time when the loop starts running and finishes running.

Then we logged the time by subtracting endTime by startTime to give us the elapsed time when the loop ran in milliseconds.

Serializing the Performance object

The performance object is serialized by the toJSON method.

We can use it as follows:

const js = window.performance.toJSON();
console.log(JSON.stringify(js));

Then we get something like:

{"timeOrigin":1579540433373.9158,"timing":{"navigationStart":1579540433373,"unloadEventStart":1579540433688,"unloadEventEnd":1579540433688,"redirectStart":0,"redirectEnd":0,"fetchStart":1579540433374,"domainLookupStart":1579540433376,"domainLookupEnd":1579540433423,"connectStart":1579540433423,"connectEnd":1579540433586,"secureConnectionStart":1579540433504,"requestStart":1579540433586,"responseStart":1579540433678,"responseEnd":1579540433679,"domLoading":1579540433691,"domInteractive":1579540433715,"domContentLoadedEventStart":1579540433715,"domContentLoadedEventEnd":1579540433716,"domComplete":1579540433716,"loadEventStart":1579540433716,"loadEventEnd":0},"navigation":{"type":0,"redirectCount":0}}

logged.

Measuring Multiple Actions

We can use the mark method to mark our actions and the use the measure method to measure the time between actions by passing in the names.

For example, we can measure time with markings as follows:

performance.mark('beginLoop');
for (let i = 0; i < 10000; i++) {
  console.log(i);
}
performance.mark('endLoop');
performance.measure('measureLoop', 'beginLoop', 'endLoop');
console.log(performance.getEntriesByName('measureLoop'));

In the code above, we called the mark method before the loop starts and after the loop ends.

Then we call the measure method with a name we create to get the time difference later and both markers so that we can get the time from them and get the time difference.

Then we called performance.getEntriesByName(‘measureLoop’) to get the computed duration with the duration property of the returned object.

‘measureLoop’ is the name we made up to get the time difference by name, and ‘beginLoop' and 'endLoop' are our time markers.

We can get entries marked by the mark method with the getEntriesByType method. It takes a string for the type. To do this, we can write:

performance.mark('beginLoop');
for (let i = 0; i < 10000; i++) {
  console.log(i);
}
performance.mark('endLoop');
performance.measure('measureLoop', 'beginLoop', 'endLoop');
console.log(performance.getEntriesByType("mark"))

Then the console.log should get us the following:

[
  {
    "name": "beginLoop",
    "entryType": "mark",
    "startTime": 133.55500000761822,
    "duration": 0
  },
  {
    "name": "endLoop",
    "entryType": "mark",
    "startTime": 1106.3149999827147,
    "duration": 0
  }
]

There’s also a getEntriesByName method which takes the name and the type as the first and second arguments respectively.

For example, we can write:

performance.mark('beginLoop');
for (let i = 0; i < 10000; i++) {
  console.log(i);
}
performance.mark('endLoop');
performance.measure('measureLoop', 'beginLoop', 'endLoop');
console.log(performance.getEntriesByName('beginLoop', "mark"));

Then we get:

[
  {
    "name": "beginLoop",
    "entryType": "mark",
    "startTime": 137.6299999828916,
    "duration": 0
  }
]

from the console.log .

We can also use getEntries by passing in an object with the name and entryType properties as follows:

performance.mark('beginLoop');
for (let i = 0; i < 10000; i++) {
  console.log(i);
}
performance.mark('endLoop');
performance.measure('measureLoop', 'beginLoop', 'endLoop');
console.log(performance.getEntries({
  name: "beginLoop",
  entryType: "mark"
}));

Then we get something like:

[
  {
    "name": "[https://fiddle.jshell.net/_display/](https://fiddle.jshell.net/_display/)",
    "entryType": "navigation",
    "startTime": 0,
    "duration": 0,
    "initiatorType": "navigation",
    "nextHopProtocol": "h2",
    "workerStart": 0,
    "redirectStart": 0,
    "redirectEnd": 0,
    "fetchStart": 0.2849999873433262,
    "domainLookupStart": 0.2849999873433262,
    "domainLookupEnd": 0.2849999873433262,
    "connectStart": 0.2849999873433262,
    "connectEnd": 0.2849999873433262,
    "secureConnectionStart": 0.2849999873433262,
    "requestStart": 2.3250000085681677,
    "responseStart": 86.29499998642132,
    "responseEnd": 94.03999999631196,
    "transferSize": 1486,
    "encodedBodySize": 752,
    "decodedBodySize": 1480,
    "serverTiming": [],
    "unloadEventStart": 101.23999998904765,
    "unloadEventEnd": 101.23999998904765,
    "domInteractive": 126.96500000311062,
    "domContentLoadedEventStart": 126.9800000009127,
    "domContentLoadedEventEnd": 127.21500001498498,
    "domComplete": 128.21500000427477,
    "loadEventStart": 128.2249999931082,
    "loadEventEnd": 0,
    "type": "navigate",
    "redirectCount": 0
  },
  {
    "name": "[https://fiddle.jshell.net/js/lib/dummy.js](https://fiddle.jshell.net/js/lib/dummy.js)",
    "entryType": "resource",
    "startTime": 115.49500000546686,
    "duration": 0,
    "initiatorType": "script",
    "nextHopProtocol": "h2",
    "workerStart": 0,
    "redirectStart": 0,
    "redirectEnd": 0,
    "fetchStart": 115.49500000546686,
    "domainLookupStart": 115.49500000546686,
    "domainLookupEnd": 115.49500000546686,
    "connectStart": 115.49500000546686,
    "connectEnd": 115.49500000546686,
    "secureConnectionStart": 0,
    "requestStart": 115.49500000546686,
    "responseStart": 115.49500000546686,
    "responseEnd": 115.49500000546686,
    "transferSize": 0,
    "encodedBodySize": 0,
    "decodedBodySize": 0,
    "serverTiming": []
  },
  {
    "name": "[https://fiddle.jshell.net/css/result-light.css](https://fiddle.jshell.net/css/result-light.css)",
    "entryType": "resource",
    "startTime": 115.77999999281019,
    "duration": 0,
    "initiatorType": "link",
    "nextHopProtocol": "h2",
    "workerStart": 0,
    "redirectStart": 0,
    "redirectEnd": 0,
    "fetchStart": 115.77999999281019,
    "domainLookupStart": 115.77999999281019,
    "domainLookupEnd": 115.77999999281019,
    "connectStart": 115.77999999281019,
    "connectEnd": 115.77999999281019,
    "secureConnectionStart": 0,
    "requestStart": 115.77999999281019,
    "responseStart": 115.77999999281019,
    "responseEnd": 115.77999999281019,
    "transferSize": 0,
    "encodedBodySize": 49,
    "decodedBodySize": 29,
    "serverTiming": []
  },
  {
    "name": "beginLoop",
    "entryType": "mark",
    "startTime": 128.3699999912642,
    "duration": 0
  },
  {
    "name": "measureLoop",
    "entryType": "measure",
    "startTime": 128.3699999912642,
    "duration": 887.0650000171736
  },
  {
    "name": "endLoop",
    "entryType": "mark",
    "startTime": 1015.4350000084378,
    "duration": 0
  }
]

from the console.log .

With markers, we can name our time markers, so we can measure multiple actions.

Clearing Actions

We can clear performance markers by calling the clearMarks method. For example, we can do that as follows:

performance.mark("dog");
performance.mark("dog");
performance.clearMarks('dog');

There’s also a clearMeasures method to clear measurements and clearResourceTimings to clear performance entries.

For example, we can use it as follows:

performance.mark('beginLoop');
for (let i = 0; i < 10000; i++) {
  console.log(i);
}
performance.mark('endLoop');
performance.measure('measureLoop', 'beginLoop', 'endLoop');
performance.clearMeasures("measureLoop");
console.log(performance.getEntriesByName('measureLoop'));

Then we should see an empty array when we call getEntriesByName .

To remove all performance entries, we can use the clearResourceTimings method. It clears the performance data buffer and sets the performance data buffer to zero.

It takes no arguments and we can use it as follows:

performance.mark('beginLoop');
for (let i = 0; i < 10000; i++) {
  console.log(i);
}
performance.mark('endLoop');
performance.measure('measureLoop', 'beginLoop', 'endLoop');
performance.clearResourceTimings();

In the code above, we called the clearResourceTimings method to reset the buffers and performance data to zero so that we can run our performance tests with a clean slate.

Conclusion

We can use the Performance API to measure the performance of a piece of front-end JavaScript code.

To do this, we can use the now method to get the timestamp and then find the difference between the 2.

We can also use the mark method to mark the time and then use the measure method to compute the measurement.

There’re also various ways to get the performance entries and clear the data.