4Geeks logo
4Geeks logo

Courses

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Coding Bootcamp

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Data Science and Machine Learning - 16 wks

Full-Stack Software Developer - 16w

Search from all Lessons

LoginGet Started
← Back to Lessons
  • Flux

  • ReactJS

Edit on Github

Learn What is React Flux

Why do we need Flux?

Remember how we always say that programming is like Taco Bell? It’s always the same ingredients, except differently! In this particular case, we are going to be relying heavily on Events to create our entire application architecture.

Why do we need Flux?

We know you are still in the process of learning React. States and props can be confusing, and now, with Flux, things are going to get a little bit harder. But it’s for a good cause!

Without Flux, you can’t create medium or big React applications because everything will become disorganized pretty quickly.

Also, two different views are not able to send data between each other like the components do (using props) because all views are siblings and React Router is instantiating them. We need to have a common store shared between all the views that we are going to call "The Store."

Here is a list of all the advantages of using it:

  • It centralizes and detaches the application data from the components: database communication and data-processing will not depend anymore on how the application looks (renders).
  • It controls the way your application data will flow: it does not matter if the data was inputted by the user or coming from a database; everything will be available in a clear and accessible way.
  • It differentiates your components in Views vs Re-usable components: your components will remain being abstracted from your application logic, making them 100% reusable for future applications.

React Flux

Flux Divides the Application in 3 Layers:

  
Views (Components)Every React Component that calls any Flux action is called a view. The reason to call those components differently is that React components are supposed to communicate with each other through their props (without Flux).

Once a React Component is hard-coded to Flux, you will not be able to reuse that component in the future (on this or any other development).
ActionsActions can be triggered components (when the user clicks or interacts with the application) or by the system (for example, the auto-save functionality). Actions are the first step of any Flux workflow, and they always need to dispatch to the store.
StoreThe store contains all the application data. It handles everything incoming from the dispatcher and determines the way data should be stored and retrieved.

Building our first User History with Flux

The following project is a To-Do List application with 2 main user stories:

  • Create task (already developed and working).
  • Delete task.

To code the delete functionality, we have to update these files: (1) The Component (for when the user clicks on the track), (2) The Actions, (3) The Store (two times), and (4) The Component one last time. It's only 3 files and 5 updates. And you have to do that for every user story that you are going to build into your application.

In the end, working with Flux has to become something as automatic as riding a bike.

react flux

Let's Implement the Delete Task Functionality

1) What user action starts the functionality?

(It’s always a typical JS event like click, hover, resize, etc.)

Everything starts whenever the user clicks on the trash can icon. That is why we need to start our application by listening to the typical onClick event on the delete button.

1// In the component that renders each to-do item we need to add a button and also an onClick listener that calls 2// the respective TodoAction.deleteTodo(task) function that we will create on the actions: 3 4<button onClick={()=>MyActions.deleteTodo(taskToDelete)}>delete</button>

2) Then we need to code our action inside the MyActions.js file like this:

1MyActions.js 2 3// In this case, we decided that this function (a.k.a action) will receive the ID of the task to be deleted. 4class MyActions extends Flux.Actions{ 5 deleteTask(taskToDelete){ 6 // Get the current list of actions from the store 7 let currentActions = MyStore.getActions(); 8 let updatedActions = currentActions.filter((task) => { 9 return (task.id != taskToDelete.id); 10 }); 11 12 this.dispatch('MyStore.setActions', updatedActions); 13 } 14}

☝ This is a class component. We strongly recommend you to use functional components and hooks instead because class components are legacy.

3) Update the store to handle that new dispatched action

1// Inside the todoStore we have a HandleActions method that contains the logic to handle each dispatched action 2// We have to add a new case to the switch with the name 'DELETE_TODO' 3// It has to match the name of the action that was dispatched 4 5handleActions(action) { 6 switch (action.type) { 7 ... 8 case 'DELETE_TODO': { 9 this.deleteTodo(action.id); 10 break; 11 } 12 } 13}

4) Inside the To-Do Store, implement the actual logic for deleting the task and emitting the changes

1 2// Anywhere on your TodoStore class, add a new method that finally deletes the task from the todo list. 3// In this case we are using the filter function because it returns the same array but only with 4// the elements that match the logical question inside the filter (task.id != id) 5 6class TodoStore extends EventEmitter { 7 ... 8 deleteTodo(id){ 9 this.todos = this.todos.filter((task)=>{ 10 // Filter all tasks that have the given id 11 return (task.id != id); 12 }); 13 this.emit('change'); 14 } 15 ... 16}

☝ This is a class component. We strongly recommend you to use functional components and hooks instead because class components are legacy.

The Result

Finally, we have a new functionality implemented into our project. To keep adding more functionalities, you just have to start the Flux coding workflow from step 1 all over again.

Click here to open demo in a new window