Skip to main content
Use effect async reactjs tutorial

How To Use React useEffect with Async

This Reactjs tutorial help to implement useEffect in an async manner. This is a react hook and replacement of class component method componentDidMount, componentDidUpdate, and componentWillUnmount – and async/await.

The React is a front-end UI library so we are totally dependent on the server-side for persistent data. We are using an API calls to get/set data from the database.

The componentDidMount() method is used to get that data before the component renders on the UI, But it’s a class-based lifecycle method, you can not use with the latest version of react with hooks.

The sample componentDidMount() method example:

// it gets the data
componentDidMount() {
    this.props.getAllData().then(data => {
        this.setState({
            newData: data,
         });
    });
}

We’ll first fire get call using componentDidMount() and set the state using this.setState() method, and finally again render the DOM.

useEffect Example

The function passed to useEffect will run after the render is committed to the screen. By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.

Its take two arguments:

  • Call back Method : This is a method which will run on mount of component.
  • property : This is a property that ll watch, onChange of property, callback method will fire.

The first method is mandatory where is second is optional, if you will not pass the second argument, then the callback method will be fired on every update regardless of what piece of state changes.

There are three options for the second argument:

  • Not Set property : We ll not pass watch property, then it ll run on each update regardless of data update.
  • Pass Empty Property : We ll pass empty array as a second argument, that tells the useEffect, to run callback method only once, when the component mount.
  • Set Property : We can also set one or more property under second argument, The useEffect watch listed property and run callback method when the property will change.

We cal also create above same functionality using useEffect:

const Listing = () => {
	const [data, setData] = useState(null);
	useEffect(() => {
		const fetchData = async () => {
		  const resp = await getAllData()
		  setData(resp)
		}
		fetchData()
	}, [])
}

We have a second argument [], which use to run only a one-time callback method when the component mount. You can also say that there are no properties we want you to watch. Just run once.

There is also some third-party library GitLab project that can be used for useEffect async operation.

Leave a Reply

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