setInterval inside ComponentDidMount, unexpected behaviour

Viewed 17

Here I'm fetching an API inside a React Component to display cat facts. I'm using setInterval function to fetch the data in every five seconds after the initial render.

But I noticed that in every five seconds my UI get rendering twice( I can see two cat facts at a time, first one get vanished instantly). Also, I checked that few times my UI getting re-rendered before the five seconds interval. Can anyone explain me this?

import { Component } from "react";

class App extends Component {
  state = { cats: " " };

  getCats() {
    fetch("https://catfact.ninja/fact")
      .then((response) => response.json())
      .then((data) => this.setState({ cats: data.fact }));
  }
  componentDidMount() {
    setInterval(() => this.getCats(), 5000);
  }
  render() {
    return <h3>{this.state.cats}</h3>;
  }
}
export default App;
1 Answers

that's because of react strict mode if you change index.js from this one

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

to this one :

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <>
    <App />
  </>
);

your problem will be solved

Related