Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to reload page without refresh in ReactJS

Introduction

Welcome back to our learning journey! Today, we'll be diving into a very interesting and frequently asked topic in the world of web development, particularly in the ReactJS realm: "How to reload a page without refreshing in ReactJS". This might sound a bit counterintuitive initially, but don't worry, we'll unpack it bit by bit and by the end of this article, you'll have a good understanding of how to implement this in your own projects.

Let's start with a bit of context. ReactJS is a JavaScript library used for building user interfaces, primarily for single-page applications. It allows developers to create reusable UI components. Now, when we talk about reloading a page without refreshing, what we really mean is updating our UI components without having to reload the entire page.

Understanding the Basics

In the traditional way of web development, when data in the server changes, the entire page often needs to be reloaded to reflect the changes. However, in modern web development, with libraries like ReactJS, we can update only the parts of the page that are affected by the data changes. This is what we mean by "reloading a page without refreshing".

To fully appreciate this, let's use an analogy. Think of your web page as a building made up of different rooms (components). Traditional web development is like tearing down the entire building and rebuilding it from scratch every time you want to change the decor in a single room. On the other hand, ReactJS allows you to just remodel the room you want, without disturbing the rest of the building.

State and Props in ReactJS

Before we dive into the code, it's important to understand two core concepts in ReactJS - State and Props.

State: This is the heart of every React component. It's an object that stores the data which determines how that component renders and behaves. When the state changes, the component responds by re-rendering.

Props: Short for properties, props are how components talk to each other. You can think of props as arguments to a function. They are passed from the parent component to the child component.

Coding Time: Reloading a Page without Refreshing

Now, let's see how we can reload a page without refreshing in ReactJS. Let's create a simple application that displays a counter. When the counter is clicked, its value increases by one.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;

In the example above, we are using the useState Hook from React to create a state variable count and a function to update it setCount. Initially, the count is set to 0. When the button is clicked, the setCount function is called with the new count, which triggers a re-render of the Counter component, but not a full page reload.

Reacting to Data Changes

In real-world applications, you will rarely have static data. Usually, your data will come from an external source like an API. In such cases, you can use the useEffect Hook to handle side effects. Side effects are basically anything that affects something outside of the scope of the function being executed.

Imagine you are cooking. The main task is to prepare the meal, but you also have to deal with side effects like washing the dishes. Similarly, in our application, rendering the UI is the main task, but we also have to deal with side effects like fetching data from an API.

Here is a simple example of how to fetch data from an API and update the UI when the data changes, without reloading the entire page.

import React, { useState, useEffect } from 'react';

function User() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch('https://api.github.com/users/octocat')
      .then(response => response.json())
      .then(data => setUser(data));
  }, []);

  return (
    <div>
      {user && (
        <>
          <p>Name: {user.name}</p>
          <p>Location: {user.location}</p>
        </>
      )}
    </div>
  );
}

export default User;

In this example, we are fetching user data from the GitHub API and storing it in the user state. The useEffect Hook takes two arguments: a function that handles side effects and an array of dependencies. When one of the dependencies changes, the function is executed. In our case, the dependency array is empty, meaning the function will only run once, similar to componentDidMount in class components.

Conclusion

And just like that, we've learned how to reload a page without refreshing in ReactJS. This is just the tip of the iceberg, but understanding this concept is fundamental to becoming proficient in ReactJS.

Remember, ReactJS is all about building efficient and responsive user interfaces. It achieves this by only updating the components that need to be updated, rather than reloading the entire page. This leads to a smoother user experience and more efficient use of resources.

Keep playing around with the code and trying new things. The best way to learn is by doing. Happy coding!