JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

How to call a function only once in React

Author:JIYIK Last Updated:2025/03/16 Views:

Use useEffecthooks to call a function only once in React. When useEffecthooks 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;

incrementNumFunction is called only once when the component is mounted.

useEffectThe 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 useEffectthe function we pass to the hook will only be called once.

注意useEffect, we defined the function inside the function passed to the hook incrementNum.

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 useEffectdefine a getUsersfunction 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.

useEffectThe 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 useCallbackthe hook to memoize the function and pass it to useEffectthe 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;

useCallbackThe 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 incrementNumthe function is stable and doesn't change between renders, we can safely add it to useEffectthe 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.

Article URL:

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.

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.

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

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial