Home ยป JavaScript ยป Load Function Using React useEffect Only Once

Load Function Using React useEffect Only Once

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(() => {
  }, []);

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

Example 2:

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

React.useEffect(() => {
.then(results => results.json())
.then(data => {
}, []); 

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

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>