0

I don't understand why when I run:

  interface Xxx {
    str: string
  }

  const [xxx, setXxx] = useState<Xxx>();

  function getData() {
    setXxx({
      str: "aaa"
    });
  }

  getData()

then the hook is being set all the time and forever. How to run getData once?

wykopowiedz1
  • 103
  • 1
  • 8

1 Answers1

3

To execute your method only once on the component init, you can use the hook useEffect :

useEffect(() => {
  getData()
}, []);

This is similar to react lifecycle method componentDidMount.

Some documentation : https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

Tkim
  • 350
  • 1
  • 8