Hi Felix!
Thanks for your port of the bloc library to React! I have a feature suggestion due to the limitations I'm facing with <BlocBuilder ... />
Is your feature request related to a problem? Please describe.
<BlocBuilder .../>
is great, but it has some limitations:
- every component that needs access to the bloc
<BlocBuilder bloc={<how_do_i_easily_get_this_bloc>} ... />
in the tree must be prop-drilled down, OR passed via useContext
. The problem with useContext
is that it doesn't update when bloc state changes (not sure why it behaves like this). For example:
const authBloc = useContext(AuthBlocContext);
console.log(authBloc.state)
// somewhere else in app
authBloc.add(AuthEvent.logIn)
this does not trigger the console.log to show the new state. However, if I use a <BlocBuilder bloc={<bloc_from_useContext>}/>
component and pass the authBloc in from the useContext, I get the most updated state. But using authBloc.state directly from the context won't give me the newest state. This has implications, for example:
- not easy to access the bloc state outside of the render body. For example, it is not easy to access the state in a
useEffect
hook (in Flutter, we can just use context to access the most updated version of the Bloc in initState)
- Finally, another drawback of
<BlocBuilder .../>
is that we are relying on a renderProp to use the state which is not a huge problem, but it is undesirable
Describe the solution you'd like
If we had a useBlocBuilder
hook instead of a <BlocBuilder ... />
component like so:
const [bloc, state]= useBlocBuilder(AuthBloc, {
condition: (previous, current) => {
// some logic here
}
})
useEffect(() => {
// easily access bloc state here with `state`
}, []}
return (
<div>{
// do stuff with state
// call events with bloc.add
}</div>
)
On top of this, we could also have a useBlocListener
hook
Not only is this much more react-ish, it's more concise and easier to use (in my opinion). AND, it still preserves the "spirit" of bloc library by using BlocBuilders, having conditions, etc.