In this article, we will see how we can implement a queue in the ReactJS application.
Approach: To implement the queue we will use a custom hook, i.e., the useQueueState hook provided by the Rooks package for React. It manages the state in the form of a queue. It takes an array as an argument and returns array items containing a list and object with attributes enqueue, dequeue, peek, and length.
Below is the step-by-step implementation of the above approach:
Modules Required:
- npm
- create-react-application
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-application demo
Step 2: After creating your project folder i.e. demo, move to it using the following command:
cd demo
Step 3: Install Rooks from npm.
npm i rooks
Open the src folder and delete the following files:
- logo.svg
- setupTests.js
- App.test.js
- index.css
- reportWebVitals.js
- App.css
Project Structure: The project should look like this:
Example: In this example, we’ll implement the data structure queue in the React JS:
index.js
import React from 'react' ; import ReactDOM from 'react-dom/client' ; import App from './App' ; const root = ReactDOM.createRoot(document.getElementById( 'root' )); root.render( <React.StrictMode> <App /> </React.StrictMode> ); |
App.js
import React, { useRef } from "react" ; import { useQueueState } from "rooks" ; export default function App() { const numberToPushRef = useRef(3); const [list, { enqueue, dequeue, peek, length }] = useQueueState([1, 2, 3]); function addToQueue() { numberToPushRef.current = numberToPushRef.current + 1; enqueue(numberToPushRef.current); } return ( <> <h1 style={{ color: 'blue' , margin: '20px' }}>Queue</h1> <div style={{ display: 'flex' , flexDirection: 'horizontal' , width: '400px' , height: '60px' , fontSize: '20px' , margin: '20px' , borderTop: '2px solid green' , borderBottom: '2px solid green' }}> {list.map((item) => { return <div style={{ width: '30px' , height: '30px' , background: '#a3fc9d' , borderRadius: '5px' , margin: '10px' , textAlign: 'center' }} key={item}>{item}</div>; })} </div> <button style={{ margin: '20px' , background: '#f69dfc' , width: '200px' , borderRadius: '5px' }} onClick={addToQueue}>enqueue</button> <button style={{ margin: '20px' , background: '#f69dfc' , width: '200px' , borderRadius: '5px' }} onClick={dequeue} warning> dequeue </button> <p style={{ color: '#e84917' , fontSize: '20px' , margin: '20px' }}>Front Element : {peek()}</p> <p style={{ color: '#175ce8' , fontSize: '20px' , margin: '20px' }}>Length of Queue : {length}</p> </> ); } |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: