Stop requesting when changing the route in ReactJs

I make an request in react js and i get data using useSelector. So in useEffect i show the message from backend after the request.

useEffect(() => {
  if (selector.response ? .message) {
    console.log(selector);
    message.success(selector.response?.message, 2);
    setLoading(false);
  }
  console.log('render');
}, [selector.response]);

The code works fine, but appears an issue when i change the page(route). Clicking on another menu item i go to another page and when i come back, the useEffect is triggered again and user again sees the message from message.success(selector.response?.message, 2);.
Question: How to stop showing the message each time after i come back to my route and to show the message just one time?

20 thoughts on “Stop requesting when changing the route in ReactJs”

  1. You have to use User Effects with Cleanup

    You need to clean up the effects from the previous render or actions. Otherwise it will hold the previous state

    You will find more details in official tutorial

    userEffect Cleanup Process

    Update Answer

    import React, {useState, useEffect} from "react";
    export default function App() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        function handleChange(val) {
          setCount(val)
        }
        window.addEventListener('load', handleChange(1))
    
        return () =>{
          handleChange(0);
          console.log(count)
        };
      })
    
      return (
        <div className="App">
          {count}
        </div>
      );
    }

    Here I take a count variable and setCount methods to set the count variable

    Inside useEffect I create a function which will be responsible for setting up count value

    Then I create an addEventListner when the page will load it will set the count value to 1

    Then I call an anonymous function for clean up things which will remove the previously set value to 0

    After that I set a console to just check if its sets the value

    So when user come back to your page again initially it will find the default value then set the dynamic value.

    You can make it more efficient way. I just give you an example

    Below I share some link which will help you to handle api response

    How to call api and cleanup response using react usereffect hooks

    Reply

Leave a Comment