Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do request on page load, react hooks

I need to do a request when the page loaded (only once). I tried to do something like

if(!array.length){doRequest())

But with this method, react does more than 1 request, and I think that it will reduce my app speed. So I need the solution of this problem. Thanks

like image 574
Alex Khanas Avatar asked Dec 17 '22 14:12

Alex Khanas


2 Answers

When working with Class Components, the solution would be to make that request in the componentDidMount lifecycle, which is only called once.

class Example extends React.Component {
  componentDidMount() {
    doRequest();
  }
  render() {
    return null;
  }
}

If you're trying to use Hooks in a functional component instead of Class components then you should use:

function Example() {
  useEffect(() => doRequest(), []);
  return null;
}

Hoping of course, that doRequest is declared in an upper scope or imported somehow.

Hope this solves your question, if you need more insight into this I found a great article about replacing lifecycle with hooks.

https://dev.to/trentyang/replace-lifecycle-with-hooks-in-react-3d4n

like image 191
Yalung Tang Avatar answered Dec 26 '22 12:12

Yalung Tang


just use useEffect Hook

  import React, {useEffect} from 'react'

     const func = () => {

         useEffect(()=> {
         doRequest()

         },[]) // empty array means it only run once


      }
like image 26
Abu Dujana Mahalail Avatar answered Dec 26 '22 12:12

Abu Dujana Mahalail