useRecoilState inside custom hooks behaves weirdly
See original GitHub issueHi there, im really excited about using Recoil because it will solve many of my scenarios with a minimal implementation 😃
But something that i thought was very intuitive doesn’t work.
I have a global state which is a query composed of key:value pairs, and i need to read this in different places of the app, but the way i update this from data is similar and it’s not as simple as setQuery(string), i need to do some processing to form this string before setting it.
So I thought, I’ll create a custom hook that would get the recoil state and have a function to process the string and then set the new recoil state.
But for some reason when I do setQuery from the RecoilState, it produces updates in an irregular manner.
Inside this custom hook I have a useEffect listening to query changes, but the first time it “reacts” to it, the query value is the previous instead of the new one.
I tried using a useRef for the state to keep it updated somewhere else, but I get the same result.
here’s a code example:
const customHook = () => {
const [query, setQuery] = useRecoilState(queryState); //string
const [deserialized, setDeserialized] = useState();
const updateQuery = (key, value) => {
const newQuery = `${query} ${key}:${value}`
setQuery(newQuery)
}
useEffect(() => {
const newDeserialized = // logic to deserialize value using query recoil state, but it's the outdated value so i get wrong results
setDerserialized(newDeserialized)
}, [query])
return [deserialized, updateQuery]
Is this just never going to work? Or am doing something wrong here?
Thanks and kind regards
Issue Analytics
- State:
- Created 3 years ago
- Comments:7
Top GitHub Comments
We use browser history from
createBrowserHistory()
and then store the location in an atom.We then mount a synchronization component right beneath our
<RecoilRoot>
:It doesn’t render anything, it just listens to history changes.
Then in your toplevel component in which you have the recoil root:
That way you have the location available in Recoil. 😄
That’s smart 😃 I think that my solution will work for now since i only need history in 2 components that are wrapped by this parent, but I’ll bookmark your solution because i think i will need something like this later on.
Thanks for the help!