Bardelman
Bardelman

Reputation: 2298

useSelector can not be called inside a callback

I'm very new with redux / toolkit.

I need fetch data using the redux hook useSelector in my react functional component but the data isn't quickly ready so it seems that useSelector will return an empty array at first , then when the data is ready , it will return the popuplated array of data.

At first , i thought useSelector could be asynchronous but it's not. Redux re-render my component each time the data i'm looking for gets its value changed and that's not suitable for my functional needs. In some cases i don't want my component to re-render (espcially when only just an atomic part of the data changes, that strangely re-render all my component as well).

What i tried first is to make my data as part of my component's state so i can decide when i want it to be updated, i made the call to useSelector inside useState as it accepts a callback

const [data, setData] = useState(()=> useSelector(...))

but i got the error :

useSelector can not be called inside a callback

Any suggestions ?

Upvotes: 4

Views: 8255

Answers (1)

Mehmet Pekcan
Mehmet Pekcan

Reputation: 288

You can use useEffect.

const selectorData = useSelector(...);
const [data, setData] = useState(selectorData);

useEffect(() => {
  setData(selectorData)
}, [selectorData])

If you do it like that, component doesn't re-render every time, it will just re-render when your selector data came.

Upvotes: 10

Related Questions