[SOLVED] React function component renders Renders on focus

Issue

I have problem with re-rendering. Every time user focuses on input it’s re-rendering, even on input. Every time user types one word, function component re-renders, but I have big data and it makes everything very slow because of that.

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [containerID, setContainerID] = useState();
  const [searchVal, setSearchVal] = useState();

  return (
    <div className="App">
      {console.log("its rendering again")}
      <input
        onInput={(e) => setSearchVal(e.currentTarget.value)}
        onFocus={(e) => setContainerID(e.currentTarget.id)}
        id={1}
      />
      <input
        onInput={(e) => setSearchVal(e.currentTarget.value)}
        onFocus={(e) => setContainerID(e.currentTarget.id)}
        id={2}
      />
      <input
        onInput={(e) => setSearchVal(e.currentTarget.value)}
        onFocus={(e) => setContainerID(e.currentTarget.id)}
        id={3}
      />
      <input
        onInput={(e) => setSearchVal(e.currentTarget.value)}
        onFocus={(e) => setContainerID(e.currentTarget.id)}
        id={4}
      />
    </div>
  );
}

Not a single function starts working just renders function return section on every focus and input. Any ideas how to stop these unwanted renders? Here is code snippet also:

https://codesandbox.io/s/funny-germain-t0h8n?file=/src/App.js:0-962

Solution

Changing state causes re-renders. You can use useRef to avoid this issue. You will get values in containerId.current and searchValue.current.

export default function App() {

    const containerId = useRef();
    const searchValue = useRef();
    
    return (
      <input
            onInput={(e) => searchValue.current = e.currentTarget.value}
            onFocus={(e) => containerId.current = e.currentTarget.id}
            id={1}
          />
    );

}

Answered By – swimshahriar

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *