sudheerj / reactjs-interview-questions

List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are coming soon!!
39.11k stars 9.28k forks source link

#122 Is it possible to use async/await in plain React? #191

Open 01abhishekjain opened 2 years ago

01abhishekjain commented 2 years ago

The answer given is:

If you want to use async/await in React, you will need Babel and transform-async-to-generator plugin. React Native ships with Babel and a set of transforms.

But, you can use it in React, like so:

function App() {
  const click = async function () {
    await Promise.resolve(123);
  };
  return (
    <div onClick={click}>lorem ipsum</div>
  );
}

What am I missing?

srini-leanfolks commented 2 years ago

Yes, we can do it.

Charlygraphy23 commented 1 year ago

@01abhishekjain if u install react with create-react-app or vite, it will provide you a template project to play with. And the project already bundled with webpack and babel and you don't have to worry about the configuration of react. In this case you can run react app normally and when you build an app by npm run build, then with the help of babel and other transpilers the code get converted to support all browsers. Now if you want to create a react project from scratch, you need to mannually create the environment like create a webpack config to provide react run environment or babel. You can still change the configuration of your react app if you use create-react-app or vite

Bhanu1776 commented 1 year ago

Yes, you can do it!