I humbly request some advise or guidance on a issue I experience with a React component that renders twice when using the useState hook.
export default function SearchTable(props) {
const [filterInput, setFilterInput] = useState("");
const handleFilterChange = e => {
const value = e.target.value || "";
setFilterInput(value);
};
console.log("Search Component - Value from filterInput ", filterInput);
return (
<form noValidate autoComplete="off">
<TextField
id="standard-basic"
label="Search Component"
value={filterInput}
// onChange={() => console.log("Search Component Rendered")} // Using this this "onChange" event, the component only renders once as it does not use the useState hook
onChange={handleFilterChange}
placeholder={"Search"}
/>
</form>
);
}
What I meant is, the App component is being rendered twice with each change. If you console.log() in the SearchComponent component, you will see that it is rendered only once with each change.
So, something is causing the App component to want to re-render. From what I can see, if looks like a CodeSandbox issue.
Ok so it turns out, (or from my limited grasp of the React hooks topic regarding useState and useEffect), that whenever useState is updated, it triggers a re-render. Some of the other posts online suggested to directly update the “filterInput” variable.
Anyways, I eventually had to implement a complete work around by just simply adding a ternarary operator that only “filterInput” was updated with the correct value.
You don’t need a workaround, everything is fine with your solution. As you’re using React Strict mode, some functions intentionally called twice:
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
Class component constructor , render , and shouldComponentUpdate methods
…
Functions passed to useState , useMemo , or useReducer