Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  19] [ 6]  / answers: 1 / hits: 17841  / 4 Years ago, sat, january 25, 2020, 12:00:00

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


More From » reactjs

 Answers
68

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


[#51275] Wednesday, January 15, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reedmustafam

Total Points: 211
Total Questions: 83
Total Answers: 105

Location: Vanuatu
Member since Wed, Oct 14, 2020
4 Years ago
;