setInterval for placeholder changing

"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import React, { useEffect, useState } from "react";
import { AiOutlineSearch } from "react-icons/ai";

const Search = ({ className }: { className: string }) => {
const placeholders: string[] = [
"Search products...",
"Search categories...",
"Search clothes...",
"Search mobile phones...",
];
const [placeholder, setPlaceholder] = useState<string>(placeholders[0]);
const [placeholderIndex, setPlaceholderIndex] = useState<number>(0);

useEffect(() => {
const interval = setInterval(() => {
setPlaceholderIndex((index) => (index + 1) % placeholders.length);
}, 3000);
return () => clearInterval(interval);
}, []);

useEffect(() => {
setPlaceholder(placeholders[placeholderIndex]);
}, [placeholderIndex]);
return (
<div className={cn("items-center", className)}>
<Input placeholder={placeholder} className="rounded-r-none" type="text" />
<Button className="rounded-l-none">
<AiOutlineSearch />
</Button>
</div>
);
};

export default Search;
"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import React, { useEffect, useState } from "react";
import { AiOutlineSearch } from "react-icons/ai";

const Search = ({ className }: { className: string }) => {
const placeholders: string[] = [
"Search products...",
"Search categories...",
"Search clothes...",
"Search mobile phones...",
];
const [placeholder, setPlaceholder] = useState<string>(placeholders[0]);
const [placeholderIndex, setPlaceholderIndex] = useState<number>(0);

useEffect(() => {
const interval = setInterval(() => {
setPlaceholderIndex((index) => (index + 1) % placeholders.length);
}, 3000);
return () => clearInterval(interval);
}, []);

useEffect(() => {
setPlaceholder(placeholders[placeholderIndex]);
}, [placeholderIndex]);
return (
<div className={cn("items-center", className)}>
<Input placeholder={placeholder} className="rounded-r-none" type="text" />
<Button className="rounded-l-none">
<AiOutlineSearch />
</Button>
</div>
);
};

export default Search;
Is this a good way to change placeholder text? 😅 or this make performance issue? Im learning react so thats why i dont know whats the proper way to impliment this logic
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server