Integrating Machine Learning Models into React Hooks Applications
Last Updated :
14 Mar, 2024
Machine learning models learn from data to recognize patterns and make predictions. TensorFlow.js enables ML in JavaScript. React Hooks helps integrate ML models into React apps. Custom Hooks handle model loading and usage. useEffect loads the model on the component mount. useState manages input data and predictions.
Integrating Machine Learning Models into React Hooks App:
Step 1: Set Up Your Project
npx create-react-app ml-react-app
cd ml-react-app
Step 2: Install Required Libraries:
Install "@tensorflow/tfjs" and "@tensorflow-models/mobilenet".
By installing "@tensorflow-models/mobilenet", you gain access to the MobileNet model implementation in TensorFlow.js. This model is optimized for mobile devices and real-time applications, making it suitable for many image classification use cases.
npm install @tensorflow/tfjs @tensorflow-models/mobilenet
Folder Structure:
Project StructureThe updated dependencies will look like this:
"dependencies": {
"@tensorflow-models/mobilenet": "^2.1.1",
"@tensorflow/tfjs": "^4.17.0",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"cors": "^2.8.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: Below is the code example.
CSS
.navbar {
background-color: #333;
padding: 10px 0;
}
.logo-container {
display: flex;
justify-content: center;
align-items: center;
}
.logo {
width: 80px;
height: auto;
}
.title {
font-size: 24px;
text-align: center;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.input-container {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}
.input-container input[type="text"] {
padding: 10px;
width: 80%;
max-width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
}
.button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.image-container {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}
.image-container img {
max-width: 100%;
max-height: 300px;
width: auto;
}
.loading-text {
text-align: center;
color: #007bff;
font-weight: bold;
}
.predictions-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 300px;
border: 1px solid #ccc;
padding: 3px;
border-radius: 5px;
background-color: #f9f9f9;
}
.predictions-container h2 {
margin-bottom: 10px;
}
.predictions-container ul {
list-style-type: none;
padding: 0;
}
.predictions-container li {
margin-bottom: 5px;
}
JavaScript
//App.js
import React,
{
useEffect
} from 'react';
import * as tf from '@tensorflow/tfjs';
import ImageClassificationComponent
from './ImageClassificationComponent';
import Nav from './Nav';
import './App.css';
function App() {
useEffect(() => {
async function checkTensorFlowReady() {
await tf.ready();
const backend = tf.getBackend();
console.log('Current Backend:', backend);
}
checkTensorFlowReady();
}, []);
return (
<div className="App">
<nav className="navbar">
<div className="logo-container">
<img src=
'https://media.geeksforgeeks.org/gfg-gg-logo.svg'
alt="Logo" className="logo" />
</div>
</nav>
<h1 className='title'>
Image Classification in React with Hooks
</h1>
<ImageClassificationComponent />
</div>
);
}
export default App;
JavaScript
// ImageClassificationComponent.js
import React,
{
useState
} from 'react';
import * as mobilenet
from '@tensorflow-models/mobilenet';
import './App.css';
const ImageClassificationComponent = () => {
const [inputUrl, setInputUrl] = useState('');
const [predictions, setPredictions] = useState([]);
const [loading, setLoading] = useState(false);
const handleInputChange = (event) => {
setInputUrl(event.target.value);
};
const handleImageSubmit = async () => {
setLoading(true);
const img = document.getElementById('img');
const model = await mobilenet.load();
const predictions = await model.classify(img);
setPredictions(predictions);
setLoading(false);
};
return (
<div className="container">
<div className="input-container">
<input
type="text"
placeholder="Enter Image URL"
value={inputUrl}
onChange={handleInputChange}
/>
<button className="button"
onClick={handleImageSubmit}>
Submit
</button>
</div>
{
loading &&
<p className="loading-text">
Loading...
</p>
}
{
inputUrl && (
<div className="image-container">
<img id="img" src={inputUrl}
alt="input" className="image" />
{
predictions.length > 0 && (
<div className="predictions-container">
<h2>Predictions:</h2>
<ul>
{
predictions.map((prediction, index) => (
<li key={index}>
{prediction.className}:
{Math.round(prediction.probability * 100)}%
</li>
))
}
</ul>
</div>
)
}
</div>
)}
</div>
);
};
export default ImageClassificationComponent;
Step 5: Run Your Application
npm start
Output:
output
Similar Reads
Integrating a ML Model with React and Flask Here, we have a task of how to integrate a machine learning model with React, and Flask. In this article, we will see how to integrate a machine-learning model with React and Flask. What is the Car Prediction Model?A car price prediction model is designed to predict selling prices based on specific
6 min read
How to Organize Large React Application and Make it Scalable ? React is a declarative, efficient, and flexible JavaScript library for building user interfaces. Itâs âVâ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is essential to organize a large react app so that it can be easil
4 min read
Building Learning Dashboard In MERN Stack Course Management App In todayâs digital age, the landscape of education is rapidly evolving. One of the most significant advancements in this transformation is the rise of course websites and learning dashboards. These tools are revolutionizing how students and educators interact with educational content, manage learnin
11 min read
Utilizing Web Workers for Background Processing in React Hooks Applications Using Web Workers for background processing in React Hooks applications offers a powerful solution to handle computationally intensive tasks without blocking the main UI thread. With React Hooks, developers can easily integrate Web Workers into their applications to perform tasks such as data proces
9 min read
How to Integrate GraphQL APIs Into Your React.js Projects Imagine a React.js world where you can specify exactly the data you need and it flows effortlessly tailored to your needs, and react can efficiently update the DOM as and when needed. No more under-fetching or over-fetching of data or wrestling with nested JSON structures.This dream becomes a realit
11 min read