React Best Practices

Handling asynchronous code

Always use async/await instead of promise chains

When writing an asynchronous function, resort to the async/await syntax rather than promise chains or callbacks.

Instead of this:

1loadProfile(id) {
2  return API.fetchProfileData(id).then(profile => {
3    this.setState({ profile })
4    this.props.navigate(`settings/profile/${id}`)
5  })
6}

It should be written like this:

1async loadProfile(id) {
2  try {
3    const profile = await API.fetchProfileData(id)
4    this.setState({ profile })
5    this.props.navigate(`settings/profile/${id}`)
6  } catch (err){
7    console.log(err)
8  }
9}

Always use try/catch blocks with Async functions

When writing an async function, wrap everything in a try/catch block.

Instead of this:

1async initializeSQLjs() {
2  const existingCode = localStorage.getItem(this.editorInputKey);
3  const SQL = await sqljs({
4    locateFile: () =>
5      `https://cdn.jsdelivr.net/npm/sql.js@1.3.0/dist/sql-wasm.wasm`,
6  });
7}

It should be written like this:

1async initializeSQLjs() {
2  try {
3    const SQL = await sqljs({
4      locateFile: () =>
5        `https://cdn.jsdelivr.net/npm/sql.js@1.3.0/dist/sql-wasm.wasm`,
6    });
7  }
8  catch (error) {
9    console.log(error);
10  }
11}

Why use async/await

To answer this we need to understand how we handled asynchronous code in javascript world before async/await.

Before async/await, we had callback functions and promises.

1const request = require('request')
2request('https://example.com', (err, res) => { 
3  if(err) 
4  { 
5    console.error(err) 
6  } else { 
7    this.setState({ profile: res.data })
8    //Rest of code....
9  }
10})

Above is the example of a callback function. In order to execute the code syncronously, we have to write the code in nested format. They do not scale well even for moderately complex asynchronous code. The resulting code often becomes hard to read, easy to break, and hard to debug.

Although promises are definitely an improvement on callbacks, they too are not without problems.

Futher reading

⌘K
    to navigateEnterto select Escto close
    Previous
    Next