Business Logic Component (BLoC) pattern was introduced by Google as a solution to handle states in Flutter applications. It allows you to reduce the workload on UI components by separating the business logic from them. And, in this article, we will discuss how we can use this BLoC pattern with React.

Benefits of Using BLoC Pattern with React

BLOC architecture diagram

  • Business logic will be separated from UI components
  • First, they will send events to the BLOC using an observer
  • After processing, after receiving the request, UI components will be notified via observables
  • The advantages of this approach

Build better component libs and design systems

Component Libs and Design Systems

Scalability

Over time, application requirements may change, and business logic can keep growing. In such situations, developers can even create multiple BLoCs to maintain the clarity of the codebase.

  • BLoC patterns are platform and environment independent so that developers can use the same BLOC pattern in many projects.

Step 04: Implementing UI components

Counter

  • It is better to have an intermediate layer to implement custom handlers to handle errors.
  • App.js
  • In the app.js file, the BLoC is initialized using the CounterBloc class. Thus, the Counter component is used by passing the BloC as a prop.

Step 01: Create a React application and structure it

Blocs, Components, and Utils

  • Remove all unnecessary code, structure the application as follows:Blocs
  • Keep all the bloc classes we need
  • Components
  • Keep the UI components
  • Utils
  • Keep utility files of the project

Final thoughts

The BLoC pattern could become an overhead for small-scale projects.

Implementation of the BLoC

The BLOC class will be responsible for implementing all subjects related to business logic.

  • In this example, it is responsible for the counter logic.
  • Create a file named CounterBloc.js inside the bloc directory and used a pipe to pass the counter to the UI components.

Step 03: Adding more beauty to BLoC by an intermediate class

Create the StreamBuilder.js inside the utils directory to handle the counter request from the UI.

  • In the AsyncSnapshot class, we can initialize a constructor, handle our data (check availability, etc. ), and handle errors.

Source