Categories
React Answers

How to Reduce State Updater Calls in React Function Component?

Spread the love

To optimize the performance of our React app, we should find ways to reduce state updater calls in React function components.

In this article, we’ll find ways to reduce state updater calls in React function components.

Reduce State Updater Calls in Function Component

To reduce state updater calls in a function component, we can use one state to store an object.

And we can use the state update function to update the object instead of using multiple state updater functions to update individual values.

For instance, we can write:

const {useState, useEffect} = React;

function App() {
  const [userRequest, setUserRequest] = useState({
    loading: false,
    user: null,
  });

  useEffect(() => {
    setUserRequest({ loading: true });
    fetch('https://randomuser.me/api/')
      .then(res => res.json())
      .then(data => {
        const [user] = data.results;
        setUserRequest({
          loading: false,
          user
        });
      });
  }, []);

  const { loading, user } = userRequest;

  return (
    <div>
      {loading && 'Loading...'}
      {user && user.name.first}
    </div>
  );
}

We have the setUserTequest function that updates a state that’s stored as an object.

It has the loading and user properties.

loading is the boolean to indicate loading.

user has the user data.

We set the loading property with setUserRequest when the useEffect callback first runs.

And in the then callback, we called our API.

And then we get the data and render it afterward.

The empty array ensures that the callback only loads when the component mounts.

Conclusion

To reduce state updater calls in a function component, we can use one state to store an object.

And we can use the state update function to update the object instead of using multiple state updater functions to update individual values

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *