Reputation: 15271
So, as the title says: how can we dispatch a redux action before rendering a component?
I have a specific case where i need some shared state chunk cleared before component renders (in that case showing “loading...”) which is done through dispatching redux action.
Now, if i dispatch it with useEffect
i get flickering of first stale/old data shown and then showing “loading...”.
So far i see 2 ways to solve it:
useLayoutEffect
- i like it but not sure if its a good practiceI might create custom Fetcher
hook but doesnt that bring it back into realm of hocs/wrapper hells?
I just want to do something before first render.
Upvotes: 4
Views: 2649
Reputation: 222840
The difference between useEffect
and useLayoutEffect
is that the latter is executed synchronously after initial render:
The signature is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.
If flickering is the only problem with useEffect
and it disappears with useLayoutEffect
then the latter should be used.
Upvotes: 2