This tutorial shows how to load function using the React useEffect only once.

 Example 1: Loading Function Using React Only Once

You can give an empty array to the useEffect as a second argument to load the function only once. Below is the code:

function MyComponent() {
  useEffect(() => {
    loadDataOnlyOnce();
  }, []);

  return
   <div>{/* ... */}</div>;
}

Example 2:

function App() {
const [user, setUser] = React.useState(null);

React.useEffect(() => {
fetch('https://randomuser.me/api/')
.then(results => results.json())
.then(data => {
setUser(data.results[0]);
});
}, []); 

return <div>
{user ? user.name.first : 'Loading...'}
</div>;
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.

Leave a Reply