F
F
fif2022-04-15 19:46:42
React
fif, 2022-04-15 19:46:42

How to stop a functional component from restarting?

I started to study hooks and caught the problem, don’t scold me please)
The bottom line is that the functional component restarts itself 60 - 70 times per second, I tried to put it in different ways and came to the conclusion that this is due to useState .

Here is the component itself:

export default function Home() {
  const [state, setState] = useState({
    info: {
      count: '',
      next: '',
      pages: '',
      prev: '',
    },
    results: [],
  });

  useEffect(() => {
    fetchData(input.value);
    console.log('start');
  });

  function fetchData(name = '', link = 'https://rickandmortyapi.com/api/character') {
    setState({
      info: {
        count: '',
        next: '',
        pages: '',
        prev: '',
      },
      results: [],
    });
  }

  return <h1></h1>;
}


I print start to the console and this is what is in the console 6259a11a9d471482539077.png

. My setState function re -renders everything and runs all the functions, thereby running itself again and again. How to avoid this so that all functions do not run?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2022-04-15
@fif

useEffect(() => {
  fetchData(input.value);
  console.log('start');
}, []);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question