I'm new to react hooks and have run into a situation which I solved, but not sure if this is a proper implementation of useEffect. I have a form with some fields (answer, question etc) with some validation, but without the implementation of useEffect below, my validation was one step behind due to the async nature of setting state. After adding useEffect and the state items to the useEffect dependency array that was fixed. But the side effect of adding items to that array was re-rendering, and thus fetchData running each time the state changed. Each time fetch data finished it wiped out the changed state of any items I was changing in the form.
My solution was a "mounted" state variable which is set to true once the fetch occurs. Then if mounted was true, I don't fetch again. This solution seems to have fixed the re-fetching issue as well as the state being one step behind. Is this a proper pattern to use or is there a better/more preferred way?
const [mounted, setMounted] = useState(false)
useEffect(() => {// reactive state
// if params.id that means we need to edit an existing faq
if(params.id && !mounted){
async function fetchData() {
await fetchFaqs();
setMounted(true);
}
fetchData();
}
checkIfFormIsValid();
}, [answer, question, section, sort, checkIfFormIsValid]);