How to stop useEffect from reloading my page every time?

Viewed 2500

For some reason my whole page reloads every time it updates the state after it gets it from the database. The page flickers and I end up at the top of the page. Why is this?

I update the entire state in other functions like sort(), that works perfect without reloading. I have put event.preventDefault() in every click handler so that shouldn't be the problem.

One of the great things with using React is to have a smooth UI without reloading so this is annoying.

function App() {
  const [contacts, setContacts] = useState({ items: [] });

  useEffect(() => {
    axios
      .get('http://localhost:5000/')
      .then((result) => {       
        setContacts({ items: result.data });
      })
      .catch((err) => console.log(err));
  }, []);

And this is the function that gets called:

const handleSubmit = (event) => {
    event.preventDefault();

    if (!id) {
      axios
        .post('http://localhost:5000/add/', input)
        .then(() => {
          setInput(emptyState);
        })
        .catch((err) => console.log(err));
    } else {
      axios
        .post(`http://localhost:5000/update/${id}`, input)
        .then(() => {
          props.updateContact(input);
          setInput(emptyState);
        })
        .catch((err) => console.log(err));
    }
    window.location = '/';
  };
1 Answers

You need to put something in your []. You can see that we passed props.name into the array in the second argument. This will now cause the effect to always run again when the name changes. If you don't pass anything it will always update and will be useless.

  useEffect(() => {
    document.title = `Page of ${props.name}`
  }, [props.name])

Related