davnicwil / react-frontload

Async data loading for React components, on client & server
451 stars 21 forks source link

useContext #32

Closed shotap closed 5 years ago

shotap commented 5 years ago

Hi, I tried to use a React Context as the store for my app but the useContext hook doesn't work inside the frontload function. any ideas?

davnicwil commented 5 years ago

Because frontloads run inside lifecycle methods (in the wrapper component introduced by the HOC), hooks won't work inside frontload functions.

What I'd suggest for now is to pass your store / update state function in as props to your frontload function, similar to how you'd do it using redux or any other state manager (see the docs and example app for inspiration).

Using hooks with frontload is something I'm looking at for a future release, this would probably be 'all in' i.e. using a useFrontload hook instead of the HOC. Haven't thought about the details deeply but I think there would probably be a way to then use hooks within that frontload function.

shotap commented 5 years ago

but with that approach i need to pass the state manager in props to all my nested components. am i missing something?

davnicwil commented 5 years ago

That's exactly right - would that be a problem?

shotap commented 5 years ago

sure. take for example this component tree:

<App>
  <A>
    <B>
      <C>
        <D>
           <E>

lets say that components A, B, C, D dont care about the state and they dont know about frontload. there is no reason why those should propagate the state manager

davnicwil commented 5 years ago

Ah, sorry I didn't understand your question, thought you were asking will the props you pass to frontload be passed into the underlying component.

If you want to provide your own state manager in props, just use a provider wrapper (maybe even wrapped in a HOC for extra neatness). You can use context under the hood to avoid the above problem. It's the same pattern react-redux connect uses for example

i.e.

<StateManagerProvider>
  {stateManager => <FrontloadComponent stateManager={stateManager} />}
</StateManagerProvider>

Your frontload function is then free to use stateManager however you want. Obviously you'd just need to use context under the hood to implement StateManagerProvider.