tlt
tlt

Reputation: 15271

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.

Upvotes: 4

Views: 2649

Answers (1)

Estus Flask
Estus Flask

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

Related Questions