1

I am aware of closures and how it works also in react function components. I am facing an issue, I have a searchCriteria state with 3 fields, for example, the state can be changed by typing in the actual input fields, or the user can choose a variant from a list, and when he does so I want to fetch data automatically. eg:

const example = () => {
    const [searchCriteria, setSearchCriteria] = useState({});

    const fetch = async () => {....}

    const handleVariantChange = (v) => {
         const s = /* some logic */
         setSearchCriteria(s);
         handleSearchClick(); // Because of closure the fetch method uses the old state
    }

    const handleSearchClick = () => {
        fetch();
    }  
}

So, as you can see in the code sample, the fetch method when we fetch right after setting state won't work, because of closures of course. Of course, the obvious thing to do is use useEffect hook and in the dependency assign the searchCriteria, but not every time this state changes I want to fetch, as the user just types in the input fields and did not click on the search button. I have many workarounds but it doesn't seem right,

  • Using useEffect on searchCritera with additional state of isVariantChose and only if it is true I am fetching.
  • Accessing the updated state inside fetch method by the setSearchCriteria((state) => fetch here as here the state is always the updated one}
  • Using ref for updated state and fetching using it

There are many ways to solve this but I really can't tell what workaround is really the best one. What do you think is the one? And moreover, it can get more complex if we talk about that issue but with child and father components.

EDIT: Just saw useEvent hook, might help with this issue?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Shlomo Levi
  • 63
  • 1
  • 8
  • React state updates are processed asynchronously, so any state values used by the fetch in the ***current*** render cycle won't have updated yet. Either use the `useEffect` hook with proper dependency to issue the fetch, or just refactor the code a bit to pass the relevant values to the fetch callback. – Drew Reese May 05 '22 at 19:59

0 Answers0