I face a challenge in React about performance and how to handle a slow function.
Basically, I have a form with 6 inputs. Each input component call the heavyCalculation() (slow function) function before the render function.
So when the user starts to type on the input field the render is very slow.
The question is how to handle this kind of situation without editing the heavyCalculation function?
I started to think about using the useMemo or useCallback hook but I am not pretty sure of myself.
App.js
import React, { useState } from "react";
import Input from "components/Input";
import Button from "components/Button";
import { Card } from "antd";
import "antd/dist/antd.css";
import * as S from "./style";
const App = () => {
const [form, setForm] = useState({ userName: "", email: "", password: "", firstName: "", lastName: "", city: "" });
const handleChange = (fieldName, value) => {
const tmpForm = { ...form };
tmpForm[fieldName] = value;
setForm(tmpForm);
};
const handleSubmit = () => {
console.log(form);
};
return (
<S.Content>
<Card title={"Sign Up"} bordered={false} style={{ width: 500, height: 450 }}>
<S.Form>
<Input value={form.userName} fieldName="userName" onChange={handleChange} placeholder="Username" />
<Input value={form.email} fieldName="email" onChange={handleChange} placeholder="Email" />
<Input value={form.password} fieldName="password" type="password" onChange={handleChange} placeholder="Password" />
<Input value={form.firstName} fieldName="firstName" onChange={handleChange} placeholder="First Name" />
<Input value={form.lastName} fieldName="lastName" onChange={handleChange} placeholder="Last Name" />
<Input value={form.city} fieldName="city" onChange={handleChange} placeholder="City" />
<Button onClick={handleSubmit} label="Submit" />
</S.Form>
</Card>
</S.Content>
);
};
export default App;
Input Component
import React from "react";
import { heavyCalculation } from "global";
import * as Antd from "antd";
const Input = ({ fieldName, value, onChange, placeholder }) => {
heavyCalculation();
const handleChange = (e) => {
onChange(fieldName, e.target.value);
};
return <Antd.Input value={value} onChange={handleChange} placeholder={placeholder} />;
};
export default Input;
heavyCalculation function
export const heavyCalculation = (num = 10) => {
for (let i = 0; i < num; i++) {
heavyCalculation(num - 1);
}
};
Thanks for the help