State Management with Redux

Prerequisite Concepts

Redux can be understood as combination of two concepts: reducer and event emitter.

Reducer

There are few Array methods that are used heavily in redux.

  • Array.map - item transformation
  • Array.filter - item filtering
  • Array.concat - item appending
  • Array.reduce - generate a single value by going through each item

The function that you pass to Array.reduce is known as reducer function, or simply reducer.

A reducer accept two parameters, prevState and currentItem, then returns newState.

js
const reducer = (prevState, currentItem) => newState;

Event Emitter

An event emitter is an object that will emit events and trigger all the subscribers listens for the event.

In its simplest form, event emitter exposes two methods, subscribe and emit.

js
const evEmitter = createEventEmitter();
evEmitter.subscribe(val => console.log(`Event emitted with value ${val}`));
evEmitter.emit('hello');
evEmitter.emit('bye');

Event emitter is used heavily in JavaScript. For instance, all DOM elements are event emitters, and that's how you respond to DOM event.

js
document
.getElementById('btn')
.addEventListener('click', () => console.log('btn is clicked!'));

How does the code of createEventEmitter looks like?

js
  • createEventEmitter utilizes closure in JavaScript. With closure, the subscribe and emit functions have access to subscribers array.
  • If closure is new to you, you can go through the closure section in JavaScript: The React Parts.
Comments

There is no comment on this post yet.

Issue on this page? Report here