Understanding React’s useEffect and useState Hooks
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (175).NET Core  (29).NET MAUI  (208)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (220)BoldSign  (15)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (67)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (101)Streamlit  (1)Succinctly series  (131)Syncfusion  (920)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (37)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (151)Chart  (132)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (633)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (41)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (508)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (597)What's new  (333)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Understanding React’s useEffect and useState Hooks

Understanding React’s useEffect and useState Hooks

React first introduced Hooks in version 16.8, and they have changed the way we write React code ever since. Hooks enable you to extract stateful logic from a functional component, allowing it to be reused and tested independently.

useState and useEffect are two of React’s most useful Hooks. Therefore, a thorough understanding of them is essential for React developers. This blog will assist you in comprehending both of these Hooks.

React useState Hook

Before the useState Hook, state management in React could only be done through class components. The useState Hook in functional components serves the same purpose as this.state/this.setState in the class components.

Consider the Counter class in the following example.

class Counter extends React.Component {
  constructor(props) {
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

In this example, the count is initially set to 0, and on a button click, the count is updated by calling this.setState().

Now, let’s look at doing the same thing with the React useState Hook.

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

As shown in the example, we must first import the useState Hook from React. Following that, we call the useState Hook from within our Counter function. The React useState Hook returns the current state and the function that updates it, which are count and setCount in our example.

Note: Remember that variables normally disappear when a function exits, but React keeps state variables, so the count variable will be preserved.

Using the useState Hook, you can declare any type of state variable. The Hook can also be used multiple times in a single component.

Syncfusion React UI components are the developers’ choice to build user-friendly web applications. You deserve them too.

React useEffect Hook

When we update a state, there can be side effects that occur in parallel with each change. Data fetch requests, direct DOM manipulations, and the use of timer functions such as setTimeout() are examples of side effects. We can use the React useEffect Hook to perform side effects in function components.

Previously, these side effects were achieved using lifecycle methods like componentDidMount(), componentDidUpdate(), and componentWillUnmount(). The useEffect Hook is a combination of all these methods. It accepts a callback function that is invoked whenever a render occurs.

Take a look at the following example to see how we can use lifecycle methods to achieve the side effects.

class Time extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
componentDidMount() {
    setInterval(
      () => this.tick(),
      1000
    );
  }
tick() {
    this.setState({
      date: new Date()
    });
  }
render() {
    return (
      <div><h2>{this.state.date.toLocaleTimeString()}</h2></div>
    );
  }
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Time />);

In this example class component, we use the lifecycle methods to set the current time. Now, let’s consider the following example to see how the useEffect Hook can be used to replace the componentDidMount() method.

import React, { useState, useEffect } from "react";
function Time() {
  const [date, setDate] = useState(new Date());
  useEffect(() => {
    setInterval(() => {
      setDate(new Date());
    }, 1000);
  }, []);
  return <div>Time: {date.toLocaleTimeString()}</div>;
}

You can see how much easier it is to implement using Hooks rather than lifecycle methods. You can play with the code here.

In React components, there are two types of side effects: those that do not require cleanup and those that do. In the previous example, no cleanup was required. Setting up a subscription, closing a socket, and clearing timers are a few common examples of side effects that require cleanup.

So, let’s see how we can use useEffect with cleanup.

A to Z about Syncfusion’s versatile React components and their feature set.

useEffect with cleanup

Cleanup in useEffect is important to prevent memory leaks.

If the useEffect() callback returns a function, useEffect() considers this to be an effective cleanup. Take a look at the following example.

import { useEffect } from 'react';
function LogMessage({ message }) {
  useEffect(() => {
    const log = setInterval(() => {
      console.log(message);
    }, 1000);
    return () => {
      clearInterval(log);
    };
  }, [message]);
  return <div>logging to console "{message}"</div>;
}

In the previous example, the cleanup function clears the interval. Rather than being called after the initial rendering, the cleanup function is called before invoking the next side-effect callback. It cleans up the previous side effect and then executes the current side effect.

If no cleanup is performed, there will be multiple console logs when only one updated log is required. Therefore, make sure to use the cleanup function in such scenarios.

Skipping effects

By default, the useEffect Hook runs after the first render as well as after each update. However, you might need to skip applying an effect in situations like when certain values haven’t changed since the last re-render.

You can easily skip applying effects by passing an array as a second argument to the useEffect Hook. As arguments, you can pass props or state values. When an argument is passed, the useEffect Hook will be executed after the initial render and only when the argument values change.

Consider the following example, in which the effect is only invoked if the variable count is updated.

useEffect(() => {
  console.log(count);
}, [count]);

If you want to run and clean up the effect only once, you can pass an empty array ([]) as the second argument.

Practical use cases of React Hooks

Now, let’s look at some real-world apps for the React useState and useEffect Hooks.

You can fetch API data only when the component mounts by using the React useState and useEffect Hooks. It is not permitted to use async directly for the useEffect function. Instead, you can define and then invoke an async function within the useEffect function.

See the possibilities for yourself with live demos of Syncfusion React components.

Refer to the following code example.

import { useEffect, useState } from 'react';
function FetchItems() {
  const [items, setItems] = useState([]);
  useEffect(() => {
    async function fetchItems() {
      const response = await fetch('/items');
      const fetchedItems = await response.json(response);
      setItems(fetchedItems);
    }
    fetchItems();
  }, []);
  return (
    <div>
      {items.map(name => <div>{name}</div>)}
    </div>
  );
}

You can also use the React useState and useEffect Hooks to display a loader while fetching data. Here’s the example code for that.

const Statistics = () => {
  const [stats, setStats] = useState([]);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const getStats = async () => {
      const stats = await getData();
      setStats(stats);
      setLoading(false);
    };
    getStats();
  }, []);

Explore the endless possibilities with Syncfusion’s outstanding React UI components.

Conclusion

In this article, we discussed how to use two of React’s most essential Hooks: useState and useEffect. If we know the correct usage, they can be used to write cleaner, reusable code. I hope this article helps you understand how these two Hooks work and when should we use them.

Thank you for reading!

The Syncfusion React suite offers over 80 high-performance, lightweight, modular, and responsive UI components in a single package. It’s the only suite you’ll ever need to construct a complete application.

If you have any questions or comments, you can contact us through our support forums,  support portal, or feedback portal. As always, we are happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed