How can we avoid re-rendering the same component repeatedly when using React Router v6?

As a beginner in react, I'm facing an issue with preventing components from re-rendering when navigating to a different page. Specifically, I want to display only text on my Signup and Login pages, but the Navbar keeps re-rendering every time I switch between links.

I have tried various configurations for react-router v6, but no matter what I do, the Navbar continues to appear below whenever I navigate. The strange part is that I haven't included the Navbar as a Route in my code, yet it shows up along with my image slider created using react-bootstrap carousel.

Here is a snippet of my App.js:

import React from 'react';
import Navbar from './Components/Navbar/Navbar';
import ImageSlider from './Components/Slideshow/ImageSlider';
import {BrowserRouter as Router, Route, Routes, Switch} from 'react-router-dom';
import Signup from './Components/Navbar/Signup';
import Login from './Components/Navbar/Login';
import './App.css';

function App() {
  return (
    <div className="App">  
    <Router>
      <Navbar></Navbar>
        <Routes>
          <Route path='/Signup' element={<Signup />}></Route> 
          <Route path='/Login' element={<Login />}></Route>
        </Routes>
      </Router>
      <ImageSlider></ImageSlider>
    </div>
  );
}

export default App;

In the above snippet, you can see how the Navbar component is being rendered even though it's not specified as a route. This behavior is causing frustration as it disrupts the intended layout of the pages.

If we take a look at the Navbar.js code:

import React from 'react';
import { MenuItems } from "./MenuItems";
import {Link,NavLink} from "react-router-dom";

class Navbar extends React.Component {
    render() {
        return(
            <nav className="NavbarItems">
                <ul className={this.state.clicked ? 'nav-menu active' : 'nav-menu'}>
                    {MenuItems.map((item,index) => {
                        return (
                            <li key={index}>
                                 <NavLink to={item.url} activeClassName="is-active" className={item.cName} style={{position: 'relative', right: 0, top: 13}}>
                                     {item.title}
                                 </NavLink>
                            </li>
                        )
                    })}
                </ul>
            </nav>
        )
    }
}

export default Navbar

The Navbar component renders a list of MenuItems which are meant to be navigation links. However, due to the unexpected re-rendering behavior, these links keep appearing even though they shouldn't be displayed when moving to the Signup or Login pages.

This issue also affects the ImageSlider component:

import React from 'react';
import "bootstrap/dist/css/bootstrap.css";
import Carousel from 'react-bootstrap/Carousel';

export default function ImageSlider() {
    return (
      <div className='slideshow' style={{ height:120}}>
        <Carousel controls={false}>
          // Code for carousel items...
        </Carousel>
      </div>
    );
  }

The ImageSlider is designed to showcase a slideshow with images, but the continuous re-rendering causes disruptions in its presentation as well.

Answer №1

With the introduction of react-router-dom v6, it is now possible to divide your components and display them only on specific routes.

Your main component, App.js, should be structured as follows:

<Router>
    <Routes>
        <Route element={
            <>
                <Navbar />
                <Outlet />
                <ImageSlider />
            </>
        }>
            // Rendered components for authenticated users
            <Route path='/home' element={<Home />}> </Route> 
        </Route>

        <Route element={<Outlet />}>
            // Components not rendered for guest users
            <Route path='/Signup' element={<Signup />}> </Route> 
            <Route path='/Login' element={<Login />}> </Route>
        </Route>            
    </Routes>
</Router>

By structuring it this way, the /home route will always include the Navbar and ImageSlider components, while guest routes will only display the specified elements.


As your application expands, it is recommended to organize these components into a separate folder called Layouts to better manage them.

  1. Auth Layout - a layout that shows common components for authenticated users
  2. Guest Layout - a layout that displays common components for guest users

This separation allows you to make use of async functions like useEffect or other hooks more efficiently.

A demonstration showcasing how this can be achieved by dividing components into separate layouts can be found here: https://codesandbox.io/s/multiple-layouts-react-7r8qu

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

Using seleniumjs to ensure that the element is ready for user input before proceeding

Currently, my application is in a state where it needs to wait for an iframe using the isElementPresent method before switching to it. The issue arises when I encounter trouble within the iFrame itself. I need to ensure that an input component within the ...

Ways to transfer a value between two different card elements

I have designed a component with three div cards side by side using bootstrap. The first card displays a list of products, and my intention is that when a product is clicked, the details should appear in the second card on the same page. However, this fun ...

How can I adjust the animation speed for ChartJS graphics?

Trying to adjust the animation speed of a pie chart in chartJS. Various methods have been attempted: numSteps: Number animationSteps: Number Chart.defaults.global.animationSteps = Number However, none of these approaches have successfully altere ...

Animate an svg icon to follow a designated path as the user scrolls

I am currently working on a project that involves animating a bee svg icon as the user scrolls through the website. The bee starts at the top and fills in a grey color line with pink as the user moves forward, and moves backward as the user scrolls back. Y ...

Utilizing a created variable within the alert function: A guide

In order to display error messages in my app, I have created the following code: function createTimer(): void { if (!timer.start) { Alert.alert(strings.reminders['date-required']) return; } else if (!timer.end) { Alert.alert(strin ...

Creating a JSON hierarchy from an adjacency list

I am currently working with adjacency data that includes ID's and Parent ID's. My goal is to convert this data into hierarchical data by creating nested JSON structures. While I have managed to make it work, I encountered an issue when dealing ...

Unable to trigger ng-click event in IE browser, while it functions properly in Chrome

<select id="from" multiple="multiple" name="list" ng-model="selectedVal"> <optgroup label= "{{geo.Geo}}" ng-repeat="geo in Geographies"> <option id="{{country.CountryKey}}" ng-repeat="country in geo.Country" ng-click="arrayPush( ...

Patience is key as you await the element to load and smoothly render the data in vue.JS

Is there a way to ensure that the graph is only rendered and filled with data after the data has been returned from the backend? Currently, even though the data is returned, the graph appears blank. Here is my JavaScript code: methods: { refresh( ...

What could be the reason my div is not being hidden in jQuery?

Creating a quiz layout for school is my current project, and I'm just getting started. My goal is to have the questions disappear once the 'next question' button is clicked. The issue arises after the second question because instead of the ...

Clicking on a radio button can trigger the selection of another radio button

I'm currently working on a form that includes 8 radio buttons - 4 for System A and 4 for System B. The options for the buttons are CF, ISO, ISO-B, and NW. My goal is to create a functionality where selecting a radio button in System A automatically se ...

Is it possible to extract individual values from the outcome of an SWR query using destructuring?

I'm encountering a simple issue with calling an external API: const fetcher = (...args) => fetch(...args).then(x=>x.json()) const {data:{results}, error} = useSWR("https://xxxxxxxxxxxxxxxx",fetcher) Every time I attempt to destructu ...

Utilizing React to adapt to varying HTML layouts while maintaining consistent component usage

How can I create an App with two different views for mobile and desktop without relying solely on CSS Media Queries? I have been searching for guidance but so far haven't found a solution. Any advice or direction on where to find documentation or oth ...

Is there a way to use jQuery to hide rows in a data table that contain a specific code, such as "1.1" or "1.2," that includes a

When using ajax, I pass data from two inputs to another page. These values are then used in a query to display the results in a data table on the main page within the success function. Now, I'm looking to implement a condition where any data containi ...

Using React with Typescript: Passing Props and Defining Data Types

As a relatively new TypeScript enthusiast, I find myself facing some challenges. Specifically, I am struggling with errors in my code and uncertain about how to properly pass props and select the correct type. Any guidance on this matter would be greatly a ...

Node JS: Despite modifying the URL, the response remains unchanged

My attempt to log in to teeSpring.com and retrieve a response from another URL using a login cookie seems to be causing an issue. Upon logging into teeSpring.com, the dashboard details are returned. However, when I try to make a GET request to the second U ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...

What is the best method for streaming files from Java to the browser while preventing the user from downloading and saving the file?

I'm new to this and feeling a bit lost. Here's the situation: I have a web app (built with JavaScript/Reactjs) and a backend (Java using Liferay API) The server contains files (File A, B, C, etc.) of various types: pdf, excel, audio, txt, etc. ...

In Cypress, I am trying to specifically choose only numerical values from a dropdown menu. However, the list contains a mix of alphanumeric and numeric values

Looking to streamline: This is my code: cy.get('[role=presentation]') cy.get('[role=row]').find('td') .get('[role=gridcell]').eq(9).click().wait(2000) cy.get('[role=listbox]').get('[role=option]& ...

Tips for preventing the line through effect on a span element when it is checked

I am working on a project that involves a list of items labeled as li. For example: <ul class="list"> <li class="checked">Groceries <span>&#215;</span></li> <li>Medicine <span>& ...