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
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
just use useEffect Hook
import React, {useEffect} from 'react'
const func = () => {
useEffect(()=> {
doRequest()
},[]) // empty array means it only run once
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With