I made a collapsible form in my React project and I’m trying to figure out if I did it right using useEffect. Will this cause me any problems? Or does it cause bad effects in terms of performance? useEffect confuses me.
My code :
const [showSearch, setShowSearch] = useState(true);
const toggleSearch = () => {
setShowSearch((prevShowSearch) => !prevShowSearch);
};
useEffect(() => {
const handleResize = () => {
if (window.innerWidth >= 650) {
setShowSearch(true);
} else {
setShowSearch(false);
}
};
// Bileşen ilk yüklendiğinde bir kere çalıştır
handleResize();
// Pencere boyutu değiştiğinde handleResize fonksiyonunu çalıştır
window.addEventListener("resize", handleResize);
// Cleanup function to remove event listener
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
Form :
<form
id="search"
role="search"
className={`topbar-searchbar ${showSearch ? "d-block" : "d-none"}`}
> //some inputs </form>
Button :
<button
className="form-search-button"
type="button"
aria-label="Search"
aria-haspopup="true"
title="Click to show search"
onClick={toggleSearch}
>
<IoIosSearch aria-hidden="true"></IoIosSearch>
</button>
I tried to solve this problem with media queries, but it was not enough to solve problem.
Example :
@media (max-width: 650px) {
.topbar-searchbar {
display: none;
}
.form-search-button {
display: block;
}
}
@media (min-width: 650px) {
.form-search-button {
display: none;
}
}