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.
jsconst reducer = (prevState, currentItem) => newState;
- reducer should be a pure function.
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
.
jsconst 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.
jsdocument.getElementById('btn').addEventListener('click', () => console.log('btn is clicked!'));
How does the code of createEventEmitter
looks like?
jsconst createEventEmitter = () => {const subscribers = [];const subscribe = (subscriber) => {subscribers.push(subscriber);};const emit = (value) => {subscribers.forEach((sub) => typeof sub === 'function' && sub(value));};return {subscribe,emit,};};const evEmitter = createEventEmitter();evEmitter.subscribe((val) => console.log(`Event emitted with value ${val}`));evEmitter.emit('hello');evEmitter.emit('bye');
createEventEmitter
utilizes closure in JavaScript. With closure, thesubscribe
andemit
functions have access tosubscribers
array.- If closure is new to you, you can go through the closure section in JavaScript: The React Parts.