In this tutorial, we will learn very important React Hooks that are useState and useEffect Hooks.
Hooks are a new addition to React 16.8. They let you use state and other React features without writing a class.When would I use a Hook?
If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component.Let's create React app step by step and understand the usage of useState and useEffect Hooks.
Side effects have common features which the most web applications need to perform, such as:
Build React JS Frontend Application
We will use VS Code IDE to build React application.
1 - Create a React UI with Create React App
The Create React App CLI tool is an officially supported way to create single-page React applications. It offers a modern build setup with no configuration.
To create a new React app, open terminal in VS Code and type the below command:
npx create-react-app react-frontend
Running any of these commands will create a directory called react-frontend inside the current folder. Inside that directory, it will generate the initial project structure and install the transitive dependencies:
react-frontend
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
Let's explore important files and folders of the react project.
For the project to build, these files must exist with exact filenames:
- public/index.html is the page template;
- src/index.js is the JavaScript entry point.
You can delete or rename the other files Let's quickly explore the project structure.
package.json - The package.json file contains all the required dependencies for our React JS project. Most importantly, you can check the current version of React that you are using. It has all the scripts to start, build, and eject our React app.
public folder - The public folder contains index.html. As react is used to build a single page application, we have this single HTML file to render all our components. Basically, it's an HTML template. It has a div element with id as root and all our components are rendered in this div with index.html as a single page for the complete react app.
src folder- In this folder, we have all the global javascript and CSS files. All the different components that we will be building, sit here.
index.js - This is the top renderer of your react app.
node_modules - All the packages installed by NPM or Yarn will reside inside the node_modules folder.
App.js - The App.js file contains the definition of our App component which actually gets rendered in the browser and this is the root component.
2 - Adding Bootstrap in React Using NPM
Open a new terminal window, navigate to your project's folder, and run the following command:
$ npm install bootstrap --save
After installing the bootstrap package, you will need to import it into your React app entry file.
Open the src/index.js file and add the following code:
import 'bootstrap/dist/css/bootstrap.min.css';
src/index.js
Here is the complete code for the index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
3. Develop a React Component
Components are the building blocks of our whole react app. They are like functions that accept inputs in terms of props, state, and outputs a UI that is rendered in the browser. They are reusable and composable.
React components can be either a function component or a class component. In this example, we are going to use the functional component with Reach Hooks.
Let's create an EmployeeComponent.js file and add the following code to it.
import React, {useState, useEffect} from 'react'
function EmployeeComponent() {
const [employees, setEmployees] = useState([])
useEffect(() => {
getEmployees()
}, [])
const getEmployees = () => {
setEmployees([
{
"id":1,
"firstName":"Ramesh",
"lastName":"Fadatare",
"email":"ramesh@gmail.com"
},
{
"id":2,
"firstName":"Tony",
"lastName":"Stark",
"email":"tony@gmail.com"
},
{
"id":3,
"firstName":"John",
"lastName":"Cena",
"email":"cena@gmail.com"
}
])
};
return (
<div className = "container">
<h1 className = "text-center"> Employees List</h1>
<table className = "table table-striped">
<thead>
<tr>
<th> Employee Id</th>
<th> Employee First Name</th>
<th> Employee Last</th>
<th> Employee Email</th>
</tr>
</thead>
<tbody>
{
employees.map(
employee =>
<tr key = {employee.id}>
<td> {employee.id }</td>
<td> {employee.firstName }</td>
<td> {employee.lastName }</td>
<td> {employee.email }</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}
export default EmployeeComponent
Let's understand the React Hooks used in the above code snippet.
useState() hook
The useState is a Hook (function) that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value. const [employees, setEmployees] = useState([])
useEffect() hook
The useEffect Hook allows us to perform side effects (an action) in the function components. It does not use components lifecycle methods that are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.Side effects have common features which the most web applications need to perform, such as:
- Updating the DOM,
- Fetching and consuming data from a server API,
- Setting up a subscription, etc.
Example: Updating DOM:
useEffect(() => {
getEmployees()
}, [])
const getEmployees = () => {
setEmployees([
{
"id":1,
"firstName":"Ramesh",
"lastName":"Fadatare",
"email":"ramesh@gmail.com"
},
{
"id":2,
"firstName":"Tony",
"lastName":"Stark",
"email":"tony@gmail.com"
},
{
"id":3,
"firstName":"John",
"lastName":"Cena",
"email":"cena@gmail.com"
}
])
// EmployeeService.getEmployees().then((response) => {
// setEmployees(response.data)
// console.log(response.data);
// });
};
4. App.js
In the previous step, we have created EmployeeComponent so let's go ahead add EmployeeComponent to App component:
import './App.css';
import EmployeeComponent from './components/EmployeeComponent';
function App() {
return (
<EmployeeComponent />
);
}
export default App;
5. Run React App
Use the below command to start the project:
npm start
Runs the app in development mode. Open http://localhost:3000 to view it in the browser.
Reference: https://reactjs.org/docs/hooks-state.html
Comments
Post a Comment
Leave Comment