Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to detect refresh event in browser ReactJS

Introduction

Welcome to our new blog post! Today, we're going to delve into the world of ReactJS, a popular JavaScript library for building user interfaces. Specifically, we're going to learn how to detect a refresh event in a browser using ReactJS.

Before we dive into the heart of the matter, let's create a shared understanding of some terms.

What is ReactJS?

ReactJS (often simply called React) is a JavaScript library for creating dynamic user interfaces. It was developed by Facebook and is now maintained by Facebook and a community of individual developers and companies. React allows developers to create large web applications that can change data, without reloading the page. It's fast, scalable, and simple, making it a favorite among developers.

What is a Browser Refresh Event?

In the context of web browsing, a refresh event is an action initiated by the user to reload the current webpage. This action could be triggered by clicking the refresh button on the browser or hitting the F5 key (or Command+R on a Mac).

Now that we've got the basics covered, let's get our hands dirty and start coding!

Setting Up Your ReactJS Environment

Before we begin, we need to ensure our ReactJS environment is ready. If you're completely new to React, don't worry! Here's a quick guide on setting up your React environment.

Install Node.js and npm: Node.js is a runtime environment that allows you to run JavaScript on your computer. npm (Node Package Manager) is a tool that will install libraries (like React) for you. You can download Node.js and npm here.

Create a new React application: Once Node.js and npm are installed, open your terminal or command prompt and type the following command:

npx create-react-app my-app

This command creates a new React application in a directory called "my-app". Feel free to replace "my-app" with the name of your choice.

  1. Navigate into your new application: Type the following command in your terminal or command prompt:
cd my-app
  1. Start your application: Type the following command:
npm start

If everything is set up correctly, your default browser should open a new tab displaying your React application.

Detecting Refresh Event in React

The key to detecting a refresh event in React lies in the lifecycle of the page. When a page is refreshed, all the state of your app is cleared out and the page is loaded as if it were the first time.

React has a built-in hook called useEffect that allows us to run side-effects during component rendering. In simpler terms, useEffect lets us perform specific actions when something happens in our app.

We want to detect the refresh event, so we will use useEffect to cause something to happen when the page loads. If the page has been refreshed, it will be loading for the "first time" and our useEffect action will happen.

Here's how we can use useEffect to detect a refresh:

import React, { useEffect } from 'react';

function App() {
  useEffect(() => {
    // This function will run when the component is first loaded
    console.log('Page has been refreshed or loaded for the first time');
  }, []);

  return (
    <div className="App">
      <h1>Welcome to my React app!</h1>
    </div>
  );
}

export default App;

In this code, the useEffect hook takes two arguments: a function and an empty array. The function contains the code we want to run. The empty array tells React to run this function only when the component is first loaded.

Differentiating Between Initial Load and Refresh

While the above code is good at detecting when the page is refreshed, it doesn't differentiate between a page refresh and the initial loading of the page. To differentiate between these two events, we can use the localStorage object.

localStorage is a web storage object that stores data with no expiration time. This data will not be deleted even when the page is refreshed.

Here's how we can use localStorage to differentiate between a page refresh and an initial load:

import React, { useEffect } from 'react';

function App() {
  useEffect(() => {
    // Check if this is the first load by seeing if our object exists in local storage
    if (localStorage.getItem('firstLoadDone') === null) {
      // If it's the first load, set the flag in local storage to true and reload the page
      localStorage.setItem('firstLoadDone', 1);
      console.log('This is the initial load');
    } else {
      console.log('This is a page refresh');
    }
  }, []);

  return (
    <div className="App">
      <h1>Welcome to my React app!</h1>
    </div>
  );
}

export default App;

In this code, we use localStorage.getItem('firstLoadDone') to check if this is the first load. If it is, we use localStorage.setItem('firstLoadDone', 1) to set a flag in local storage. The next time the page is loaded, we check this flag. If it exists, we know this is a refresh, not the initial load.

Conclusion

And that's it! We've learned how to detect a refresh event in a browser using ReactJS. We started by understanding what ReactJS is and what a browser refresh event is. Then, we moved onto setting up our ReactJS environment and getting our hands dirty with some code. We learned how to use the useEffect hook and the localStorage object to differentiate between a page refresh and the initial loading of the page.

Remember, practice makes perfect. Don't hesitate to experiment with the code and try out different things. The more you play around with it, the better you'll understand it. Happy coding!