BLoC pattern explanation with ReactJS

Indie Dev
2 min readNov 29, 2021

In React, there are different options for managing state — redux/mobx/recoil. One of pattern is not really popular in React ‘s world is BLoC pattern — which is very popular in Flutter.

So I decided to write a series about this pattern. First of all, I will try to explain what is BLoC and the basic implementation of it with simple example.

So … What is BLoC?

B(Business)L(Logic)o(of)C(component) — as name says, provides us a way to centralize all the business logic in a separate class. We can have many BLoC in a page.

Event like Action, State is State

BLoC takes event as input, process it inside BLoC, and based on the business logic it produces the correct state as output

How BLoC implements

  • The main actor of BLoC is Stream. BLoC converts whatever events added to that stream to the state stream, and after every new state, UI will changes correctly.
Flow
  • When clicking on the button, it will trigger a handler to emit the IncreaseVolumeEvent -> push to the EventStream -> BLoC will process the event -> Update new state -> Push to the State Stream -> UI listen and render again.

Basic Implementation

We will use rxjs as a stream

1/ Define the events

2/ Define the State

3/ Define BLoC

Yeah it is done !

But … how to use it with React?

Create a new instance Bloc and call it inside with useObservable hook

For the useObservable hook, you can take a look at my repo here https://github.com/namKolo/hookdafish/blob/master/src/useObservable/index.ts

For the full repo, you can take a look at https://github.com/namKolo/bloc-in-react

I will write about the clean architecture using BLoC — and implement the base class for it then we can reuse easier.

--

--