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/[email protected]/umd/react.development.js"></script> <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script> <div id="app"></div>