Import useState from react in component file
First, let's get our development environment ready. The setup script has already created a new React project for you at ~/project/my-app using Vite.
Your first task is to install the necessary dependencies and start the development server. Open a terminal in the WebIDE and run the following commands one by one.
Navigate into your project directory:
cd my-app
Install the project dependencies:
npm install
Start the development server:
npm run dev -- --host 0.0.0.0 --port 8080
After running the last command, you will see output indicating that the server is running. You can now view your live application by clicking on the "Web 8080" tab in the LabEx interface. Throughout this lab, we will be modifying the ~/project/my-app/src/App.jsx file.
In this step, we will begin by importing the useState Hook from the React library. Hooks are special functions, and to use them, you must first import them from the react package.
Using the file explorer in the WebIDE, navigate to and open the file ~/project/my-app/src/App.jsx.
First, let's clean up the default content to have a minimal starting point. Replace the entire content of App.jsx with the following code:
function App() {
return (
<>
<h1>React Counter</h1>
</>
);
}
export default App;
Now, add the import statement at the very top of the file to make the useState Hook available within our component.
import { useState } from "react";
function App() {
return (
<>
<h1>React Counter</h1>
</>
);
}
export default App;
This line tells JavaScript that we want to use the useState function, which is a named export from the 'react' library.