Skip to content
Advertisement

Why do I have to manually refresh the page for the component to load when using react-router?

enter image description hereI have a React application that uses react-router-dom to load different components from the sidebar. Whenever I click the link in the sidebar, the URL changes, but I must manually refresh the page to get the actual content of the page to load.

I want my application to automatically refresh the page when a sidebar link is clicked instead of the user having to manually refresh the page in order for a component to load.

JavaScript

This is my App.js

JavaScript

This is my Sidebar.js

JavaScript

This is the Layout.js that renders the page.

JavaScript

Contact Page Code

Advertisement

Answer

Issue

Your app code is actually crashing when navigating away from a page. It’s not clear why you aren’t seeing the React error page (perhaps you are running a production build) but the issue is that for each page you are using a useEffect hook to set a timeout to update some local state.

JavaScript

The issue with this is that React assumes that anything returned from the useEffect hook is a cleanup function to be invoked when the component is rerendering/unmounting. setTimeout returns a number representing the timer id.

Reloading the page is effectively reloading the entire app on the current URL path.

Solution

On each of these pages, refactor the logic to return a cleanup function that clears the timeout.

JavaScript

This allows the timeout to be instantiated when the component mounts, and for the offhand chance the user navigates away from the page and this component unmounts, it will clear the timeout and won’t invoke the callback that will enqueue a state state.

Suggestion

It seems that each of these pages has the same animation letterClass state for the AnimatedLetters component. Instead of duplicating the same code/logic across all pages, abstract it into a custom React hook that returns the letterClass value.

Example:

JavaScript

In each page component import the useLetterClass hook, call, and pass the returned letterClass prop value.

Example:

JavaScript

Edit why-do-i-have-to-manually-refresh-the-page-for-the-component-to-load-when-using

The sandbox code you provided also seems to have an issue with some of the SCSS, specifically with a $sidebar-color variable missing. I’m not familiar with SCSS much, but I don’t suspect it is related to the routing/navigation issue I described above.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement