Search code examples
reactjsaxiosuse-effect

How can I fetch data only once with render?


I'm trying to fetch data only once at the beginning of the rendering, I'm trying to use start variable to control in case I need to fetch again

const [data, setData] = useState();
const [start, setStart] = useState(true);

const getData = async () => {
    console.log('getting data');
    const res = await axios.get(url);
    setData(res.data);
    setStart(false);
};

let count = 0;

useEffect(() => {
  if (start === true) {
    getData();
    console.log('Render: ', count);
    count++;
  }, [start])

count is just to count the renderers, and I'm getting more than one, always, even without dependencies in the useEffect hook I get 2.

Do you have any suggestions?


Solution

  • There is many different options:

    • first of all - if you will create useEffect with empty array of dependieces it will be called one, but please
    • you can store in state that component has not been initliazed and data was not loaded
    • you can use https://github.com/streamich/react-use - there is useEffectOnce or useMount

    EDITED--------

    BTW. regarding count === 2 that part of code looks ok, I guess that you mount and unmount that component then it will be recreated from the scratch