How to call a function only once in React
Use useEffect
hooks to call a function only once in React. When useEffect
hooks is passed an empty dependencies array, it runs only when the component mounts. This is the preferred method when we have to fetch data when the component mounts.
import {useEffect, useState} from 'react';
const App = () => {
const [num, setNum] = useState(0);
useEffect(() => {
// 👇️ only runs once
console.log('useEffect ran');
function incrementNum() {
setNum(prev => prev + 1);
}
incrementNum();
}, []); // 👈️ empty dependencies array
return (
<div>
<h2>Number is {num}</h2>
</div>
);
};
export default App;
incrementNum
Function is called only once when the component is mounted.
useEffect
The second argument we pass to the hook is an array of dependencies.
The first argument is a function that is called when the component mounts and when the dependencies in the array change.
We specify an empty dependency array, so useEffect
the function we pass to the hook will only be called once.
注意
useEffect
, we defined the function inside the function passed to the hookincrementNum
.
We do this so we don't have to add the function to the hook's dependencies array.
Alternatively, we can define the function outside of the component or memoize it.
Here's an example of how you can call a function to fetch data only once - when the component mounts.
import {useEffect, useState} from 'react';
const App = () => {
const [data, setData] = useState({data: []});
const [err, setErr] = useState('');
useEffect(() => {
// 👇️ this only runs once
console.log('useEffect ran');
// 👇️ fetch data from remote API
async function getUsers() {
try {
const response = await fetch('https://www.jiyik.com/api/users', {
method: 'GET',
headers: {
Accept: 'application/json',
},
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
console.log('result is: ', JSON.stringify(result, null, 4));
setData(result);
} catch (err) {
setErr(err.message);
}
}
getUsers();
}, []); // 👈️ empty dependencies array
console.log(data);
return (
<div>
{err && <h2>{err}</h2>}
{data.data.map(person => {
return (
<div key={person.id}>
<h2>{person.email}</h2>
<h2>{person.first_name}</h2>
<h2>{person.last_name}</h2>
<br />
</div>
);
})}
</div>
);
};
export default App;
We useEffect
define a getUsers
function in the hook. This function is called only once - when the component mounts and makes a single request to the remote API to get some data.
useEffect
The hook runs only once because we pass an empty dependencies array as the second argument to it.
An alternative to defining a function inside the useEffect hook that we only want to call once is to define that function outside of the component.
If the function is defined outside of the component, it will not be recreated every time the component renders and will remain stable, so it does not have to be added to the hook's dependencies array.
Alternatively, we can use useCallback
the hook to memoize the function and pass it to useEffect
the dependencies array of .
import {useCallback, useEffect, useState} from 'react';
const App = () => {
const [num, setNum] = useState(0);
// 👇️ memoize function (doesn't get re-created every render)
const incrementNum = useCallback(() => {
setNum(prev => prev + 1);
}, []);
useEffect(() => {
// 👇️ this only runs once
incrementNum();
// 👇️ include it in the dependencies array
}, [incrementNum]);
return (
<div>
<h2>Number is {num}</h2>
</div>
);
};
export default App;
useCallback
The hook takes an inline callback function and an array of dependencies and returns a memoized version of the callback that only changes if one of the dependencies changes.
Now that incrementNum
the function is stable and doesn't change between renders, we can safely add it to useEffect
the dependencies of the hook and it will still only run once.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:99 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:187 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:85 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap