0

I have the problem that when I enter something in the title field, the preview array is re-rendered for each letter. Anyway, the images are rearranged with each typing. I have no idea what the problem is. emphasized text

  const [imagePreviews, setImagePreviews] = useState<Array<string>>([]);
  const [title, setTitle] = useState("");

  const willUpload = useCallback(
  async (e: React.ChangeEvent<HTMLInputElement>) => {
  try {
    let images: Array<string> = [];

    let files = e.target.files;
   
    for (let i = 0; i < files!!.length; i++) {
      images.push(URL.createObjectURL(files!![i]));
    }

    setImagePreviews(imagePreviews.concat(images));
  } catch (error) {
    console.log(error);
    }
   },
   [imagePreviews, uploadFiles]
 );


   return(
      ...
 
   <input
        onChange={(e) => setTitle(e.target.value)}
        type="text"
        value={title}
        placeholder="Title"
        ...
    >
   </input>
   <input
      ...
      type="file"
      multiple
      onChange={(e) => willUpload(e)}
   ></input>
     ...
     {imagePreviews.length > 0 && (
     <>
      <p className="font-semibold text-2xl text-center">Preview</p>
      <div className="grid grid-flow-row-dense grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-2 w-full p-4">
        {imagePreviews.map((preview, index) => (
          <div>...</div> 
         ))}
     </div>
    </>
    )
Captai-N
  • 1,124
  • 3
  • 15
  • 26

1 Answers1

1

There is no problem, this is how React works. It rerenders on state change.

If you want to prevent rerenders there are few techniques you can use.

  • if the view does not need that state, separate the state in different component
  • use React.memo
  • use React.useMemo
Oktay Yuzcan
  • 2,097
  • 1
  • 6
  • 15