So basically my problem is that I have two pages/screens (Main & Edit). In Main page when I click an item then it passes it to Edit page using useHistory hooks from react-router-dom package. In Edit page I get the item using useLocation hooks & pass them to input field for my initial useState, but every time I edit/type a character in text field not sure if its called re render or anything else, but the useLocation will be passed in console. Here is my code:
Edit Page/Screen
import axios from "axios";
import React, { useState } from "react";
import { useLocation } from "react-router";
export const EditScreen = () => {
const location = useLocation().state;
console.log(location);
const [title, setTitle] = useState(location.b_title);
const [content, setContent] = useState(location.b_content);
const [category, setCategory] = useState(location.category_id);
const submitHandler = (e) => {
e.preventDefault();
axios
.put(`http://localhost:3001/api/v1/blog/${location.id}`, {
blog_title: title,
blog_content: content,
category_id: category,
})
.then(alert("success edit blog"))
.catch((err) => alert(err));
setTitle("");
setContent("");
setCategory("");
};
return (
<div>
<h1>edit blog page</h1>
<form onSubmit={submitHandler}>
<input
type="text"
placeholder="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<br />
<br />
<input
type="text"
placeholder="content"
value={content}
onChange={(e) => setContent(e.target.value)}
/>
<br />
<br />
<input
type="text"
placeholder="category"
value={category}
onChange={(e) => setCategory(e.target.value)}
/>
<br />
<br />
<input
type="submit"
value="submit"
disabled={
title === "" || content === "" || category === "" ? true : false
}
/>
</form>
</div>
);
};
Screen Shot of Console
You can see above ss in red circle, thats the problem.
Bro, We cant prevent the setState from re-rendering the component as it's the react specified default before. So you must use the debouncing technique to prevent the multiple re-renders from happening https://www.telerik.com/blogs/debouncing-and-throttling-in-javascript u can go through this article for better clarity of how you can do that. It's mentioned with examples clearly in the article. You can also change the event to onBlur instead of onChange we reduce the number of setStates from getting called & we reduces the re-rendering.