The code was alright before I tried to used the setState function which is setcategory and setvalue in this code but after I did this my react page went blank. What went wrong and how should I fix it?
import Employee_card from './Employee_card'
import '../styles/home.css'
import {
Link,
useSearchParams
} from 'react-router-dom'
const Employee_dir:React.FC <props> = (employes) => {
const [category, setcategory] = useState("")
const [value, setvalue] = useState("")
let [searchParams]=useSearchParams();
if(searchParams){
setcategory(searchParams.get('category')!)
setvalue(searchParams.get('value')!)
}
return (
<div>
Some code here which is alright
<div/>
)
}```
export default Employee_dir
CodePudding user response:
wrap it around a useEffect
useEffect(() => {
if(searchParams){
setcategory(searchParams.get('category')!)
setvalue(searchParams.get('value')!)
}
}, [searchParams])
CodePudding user response:
This line is the causing this issue
if(searchParams){
setcategory(searchParams.get('category')!)
setvalue(searchParams.get('value')!)
}
Here an infinite render loop will happen if searchParams is true. (state update in react will cause the component code to execute again(re-render)). To avoid this you can wrap it in a useEffect block,
useEffect(()=> {
if(searchParams){
setcategory(searchParams.get('category')!)
setvalue(searchParams.get('value')!)
}
}, [searchParams])
Here the useEffect block will only execute (state updation of category and value) if searchParams value changes