Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatch redux action before render with react hooks

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:

  1. useLayoutEffect - i like it but not sure if its a good practice
  2. redefine redux model - that one i would like to avoid plus it sounds a bit wierd

I 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.

like image 395
dee zg Avatar asked Oct 28 '25 07:10

dee zg


1 Answers

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.

like image 200
Estus Flask Avatar answered Nov 04 '25 11:11

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!