genetic-orange
genetic-orange9mo ago

How to properly use setFilters function provided from useSimpleList

I have the following code useEffect(() => { setFilters([ { ..... } ]); }, [setFilters]); It seems it is being rendered constantly, I think there is a problem with dependences, how should I proper call setFilters?
2 Replies
kapa.ai
kapa.ai9mo ago
Hi @Facu. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- The setFilters function updates the state and triggers a re-render. If it's called inside useEffect without any dependencies, it will indeed cause an infinite loop of re-renders. To avoid this, you can use a state variable to track if it's the first render. Here's how you can modify your component to set a filter on mount without causing infinite re-renders:
import { useEffect, useState } from "react";

// ...

const [initialRender, setInitialRender] = useState(true);

useEffect(() => {
if (initialRender) {
setFilters([
{
// your filter settings
}
]);
setInitialRender(false);
}
}, [setFilters, initialRender]);
import { useEffect, useState } from "react";

// ...

const [initialRender, setInitialRender] = useState(true);

useEffect(() => {
if (initialRender) {
setFilters([
{
// your filter settings
}
]);
setInitialRender(false);
}
}, [setFilters, initialRender]);
In this code, setFilters is only called on the first render, preventing an infinite loop. The initialRender state variable is used to track whether it's the first render. After setFilters is called, initialRender is set to false, so setFilters won't be called again on subsequent renders. This information is based on the extract from a Discord support thread (https://discord.com/channels/837692625737613362/1174900517168758834). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai9mo ago
<@411223164698492929> kapa.ai is still learning and improving, please let us know how it did by reacting below