An Introduction to
Redux
Amin Ashtiani
Why you should use
redux?
1. React was designed to create UI component and each
component internally manage their state without any need
for an external library or tool and it’s a problem when our
application grow bigger
2. About shared state among component, it’s hard to detect
where is state live
3. When a shared state changed , it should lifted up to
nearest parent component which is common between the
other components and then pass down to the other child
What is Redux?
Redux is a predictable state container for JavaScript applications. It helps you write applications that
behave consistently, run in different environments (client, server, and native), and are easy to test.—
https://redux.js.org/
➔ Predictable state updates
entire state of an application is stored in one central location.
➔ "pure" reducer functions
makes it easier to implement things like logging changes to the data,
or persisting data between page refreshes
➔ Centralizing the state
makes it easier to implement things like logging changes to the data,
or persisting data between page refreshes
Misconception
There is a common misconception that
Redux was made to work with React and
just that but as you see in definition of
redux , it can use in client, server and
native.
Redux is a state container for any vanilla
JavaScript application.
How it is
working?
The way Redux works is simple. There is a
central store that holds the entire state of the
application. Each component can access the
stored state without having to send down
props from one component to another.
How it is working?
There is three building part:
1. Store
2. Action
3. Reducer
Tip
Remember. If something
sounds like common
sense, people will
ignore it.
Highlight what is
unexpected about
your topic.
Action is a plain object like
this:
1. It should have a type property, and you can
send data with payload,
2. Each action created by action creator
3. You should pass this object to
store.dispatch()
Tip
Simply put, actions are
events. User interactions
, Api calls , …
Remember that actions
only describe what
happened.
Action in Use
1st step 2nd step 3th step
Define action types
Types should typically
be defined as string
constants
Define Action Creator
action creators simply return an
action
Dispatch an action
Dispatch your action
whenever needed
Example
Reducers
specify how the application's state
changes in response to actions sent
to the store.
How it is working?
Reducers are pure functions that take:
1. the current state of an application,
2. perform an action
3. returns a new state
Tip
A pure function is a
function which:
1. Given the same input, will
always return the same
output.
2. Produces no side effects.
Side Effects
A side effect is any application state change that
is observable outside the called function other
than its return value.
Side effects are mostly avoided in functional
programming, which makes the effects of a
program much easier to understand, and much
easier to test.
1. Modifying any external variable or object
property (e.g., a global variable, or a
variable in the parent function scope
chain)
2. Logging to the console
3. Writing to the screen
4. Writing to a file
5. Writing to the network
6. Triggering any external process
7. Calling any other functions with side-
effects
Example
Example
Store
A store holds the whole state tree of
your application. The only way to
change the state inside it is to
dispatch an action on it.
A store is not a class. It's just an
object with a few methods on it
Data Flow
1. You dispatch an action
2. The Redux store calls the
reducer function you gave it
3. The root reducer may combine
the output of multiple reducers
into a single state tree
4. The Redux store saves the
complete state tree returned by
the root reducer.
Example
Presentational and Container Components
Simple implementation of container
Example
Example
Example
Features Redux MobX GraphQL Jumpsuit
DRY principle No Yes Yes Yes
Complication High Low Medium Medium
Learning curve High Low Medium Low
Application Suitable for
simple
application
Suitable for
complex
application
Suitable for
medium sized
application
Suitable for
complex
application
Comparison Table of Redux Alternatives
Question:
But how Redux
deals with async
action?
Async Flow
For handling Async action we need a
Middleware.
Asynchronous middleware like redux-
thunk or redux-saga wraps the store's
dispatch() method and allows you to
dispatch something other than
actions, for example, functions or
Promises.
Pros and Cons of Redux-Thunk
● Hard to scale
● No built in way
to handle
advance task
● Action creators
are impure
● Easy to learn
● Everything is
basic
javascript(makes it
easy to integrate)
Pros and Cons of Redux-Saga
● quite confusing
at times
● sagas live
outside of your
other redux
logic
● lot of useful
helper functions
for advance task
● heavy use of
ES6
Pros and Cons of Redux-Observable
● quite confusing
at times
● Esoteric testing
● useful helper
functions for
advance task
● heavy use of
ES6
Pros and Cons of Redux-Loop
● No built in way
to handle
advance task
like debouncing
● Easy to follow
the flow of
action
● Everything
remain pure
Conclusion!
If you want something powerful use Redux-
saga or Redux-Observable
If you want something with small learning
curve use redux-thunk
For small personal projects use Redux-Loop

an Introduction to Redux

  • 1.
  • 2.
    Why you shoulduse redux? 1. React was designed to create UI component and each component internally manage their state without any need for an external library or tool and it’s a problem when our application grow bigger 2. About shared state among component, it’s hard to detect where is state live 3. When a shared state changed , it should lifted up to nearest parent component which is common between the other components and then pass down to the other child
  • 3.
    What is Redux? Reduxis a predictable state container for JavaScript applications. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.— https://redux.js.org/ ➔ Predictable state updates entire state of an application is stored in one central location. ➔ "pure" reducer functions makes it easier to implement things like logging changes to the data, or persisting data between page refreshes ➔ Centralizing the state makes it easier to implement things like logging changes to the data, or persisting data between page refreshes
  • 5.
    Misconception There is acommon misconception that Redux was made to work with React and just that but as you see in definition of redux , it can use in client, server and native. Redux is a state container for any vanilla JavaScript application.
  • 6.
    How it is working? Theway Redux works is simple. There is a central store that holds the entire state of the application. Each component can access the stored state without having to send down props from one component to another.
  • 7.
    How it isworking? There is three building part: 1. Store 2. Action 3. Reducer Tip Remember. If something sounds like common sense, people will ignore it. Highlight what is unexpected about your topic.
  • 8.
    Action is aplain object like this: 1. It should have a type property, and you can send data with payload, 2. Each action created by action creator 3. You should pass this object to store.dispatch() Tip Simply put, actions are events. User interactions , Api calls , … Remember that actions only describe what happened.
  • 9.
    Action in Use 1ststep 2nd step 3th step Define action types Types should typically be defined as string constants Define Action Creator action creators simply return an action Dispatch an action Dispatch your action whenever needed
  • 10.
  • 11.
    Reducers specify how theapplication's state changes in response to actions sent to the store.
  • 12.
    How it isworking? Reducers are pure functions that take: 1. the current state of an application, 2. perform an action 3. returns a new state Tip A pure function is a function which: 1. Given the same input, will always return the same output. 2. Produces no side effects.
  • 13.
    Side Effects A sideeffect is any application state change that is observable outside the called function other than its return value. Side effects are mostly avoided in functional programming, which makes the effects of a program much easier to understand, and much easier to test. 1. Modifying any external variable or object property (e.g., a global variable, or a variable in the parent function scope chain) 2. Logging to the console 3. Writing to the screen 4. Writing to a file 5. Writing to the network 6. Triggering any external process 7. Calling any other functions with side- effects
  • 14.
  • 15.
  • 16.
    Store A store holdsthe whole state tree of your application. The only way to change the state inside it is to dispatch an action on it. A store is not a class. It's just an object with a few methods on it
  • 17.
    Data Flow 1. Youdispatch an action 2. The Redux store calls the reducer function you gave it 3. The root reducer may combine the output of multiple reducers into a single state tree 4. The Redux store saves the complete state tree returned by the root reducer.
  • 18.
  • 19.
    Presentational and ContainerComponents Simple implementation of container
  • 20.
  • 21.
  • 22.
  • 25.
    Features Redux MobXGraphQL Jumpsuit DRY principle No Yes Yes Yes Complication High Low Medium Medium Learning curve High Low Medium Low Application Suitable for simple application Suitable for complex application Suitable for medium sized application Suitable for complex application Comparison Table of Redux Alternatives
  • 26.
  • 27.
    Async Flow For handlingAsync action we need a Middleware. Asynchronous middleware like redux- thunk or redux-saga wraps the store's dispatch() method and allows you to dispatch something other than actions, for example, functions or Promises.
  • 29.
    Pros and Consof Redux-Thunk ● Hard to scale ● No built in way to handle advance task ● Action creators are impure ● Easy to learn ● Everything is basic javascript(makes it easy to integrate)
  • 30.
    Pros and Consof Redux-Saga ● quite confusing at times ● sagas live outside of your other redux logic ● lot of useful helper functions for advance task ● heavy use of ES6
  • 31.
    Pros and Consof Redux-Observable ● quite confusing at times ● Esoteric testing ● useful helper functions for advance task ● heavy use of ES6
  • 32.
    Pros and Consof Redux-Loop ● No built in way to handle advance task like debouncing ● Easy to follow the flow of action ● Everything remain pure
  • 33.
    Conclusion! If you wantsomething powerful use Redux- saga or Redux-Observable If you want something with small learning curve use redux-thunk For small personal projects use Redux-Loop

Editor's Notes

  • #14 Sometimes we can avoid side-effects. Imagine when you want to insert a data into database.
  • #15 We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead. We return the previous state in the default case. It's important to return the previous state for any unknown action.
  • #16 We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead. We return the previous state in the default case. It's important to return the previous state for any unknown action.
  • #17 The store has the following responsibilities: Holds application state; Allows access to state via getState(); Allows state to be updated via dispatch(action); Registers listeners via subscribe(listener); Handles unregistering of listeners via the function returned by subscribe(listener). It has 4 method: getState : Returns the current state tree of your application. It is equal to the last value returned by the store's reducer. Dispatch : Dispatches an action. This is the only way to trigger a state change. Subscribe : Adds a change listener. It will be called any time an action is dispatched, and some part of the state tree may potentially have changed.It is a low-level API. Most likely, instead of using it directly, you'll use React (or other) bindings replaceReducer : Replaces the reducer currently used by the store to calculate the state. It is an advanced API. You might need this if your app implements code splitting, and you want to load some of the reducers dynamically. You might also need this if you implement a hot reloading mechanism for Redux.
  • #19 We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead. We return the previous state in the default case. It's important to return the previous state for any unknown action.
  • #21 We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead. We return the previous state in the default case. It's important to return the previous state for any unknown action.
  • #22 We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead. We return the previous state in the default case. It's important to return the previous state for any unknown action.
  • #23 We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead. We return the previous state in the default case. It's important to return the previous state for any unknown action.
  • #24 Flux is a pattern and Redux is a library. Flux is a fancy name for the observer pattern modified a little bit to fit React, but Facebook released a few tools to aid in implementing the Flux pattern, so the following is the difference between using these tools (which is commonly referred to as using Flux) and using Redux.
  • #28 Any middleware you use can then intercept anything you dispatch, and in turn, can pass actions to the next middleware in the chain. For example, a Promise middleware can intercept Promises and dispatch a pair of begin/end actions asynchronously in response to each Promise. When the last middleware in the chain dispatches an action, it has to be a plain object. This is when the synchronous Redux data flow takes place.
  • #30 Redux-Thunk is really easy to learn as there are literally no new concepts involved at all. Everything is basic javascript and therefore makes it easy to pick up and integrate into your application. On the flipside it does not scale that well and as the amount of your async logic grows you might end up with rather complicated code. Furthermore it might no longer be obvious, which action creators are pure and which have sideeffects attached to them, which further complicates the flow of your application logic (although naming conventions might help to lessen this issue). Also there is no built in way to handle advanced tasks like throttling, debouncing or cancellation.
  • #31 Redux-Saga is an immensely powerful tool that comes packed with a lot of useful helper functions. E.g. it already has built in ways to handle advanced tasks like throttling, debouncing, race conditions and cancellation. It is also very well documented. The downsides are that you really have to understand generator functions first. While these are a powerful tool in you belt, they are currently rarely used outside of the Redux-Saga world, which means that this particular skill might not be as transferable to other fields as lets say Redux-Observable, which is built on reactive streams. Redux-Saga code also tends to be rather imperative. Depending on your personal preferences this might be either a pro or a con. Another painpoint with sagas is testing. It is certainly doable, but can be quite confusing at times. Because sagas live outside of your other redux logic it also might not always be obvious, where sideeffects actually happen.
  • #32 Redux-Observable basically shares most of the pros and cons of Redux-Saga. It ist very powerful, has cancellation, throttling etc. already baked in, but comes with a steep learning curve and somewhat esoteric testing via a testScheduler. Another downside to Redux-Observable is, that your async logic again is separated from your other redux related code.
  • #33  Because our async handling resides directly next to our other redux logic it is really easy to follow the flow of actions. Commands just declaratively describe effects and so our reducers as well as our action creators remain pure functions. This makes our code easily testable (Redux-Loop comes with a few helper functions for testing commands as well). Another big pro is that there are just a few new concepts to learn. I assume that most developers will be able to pick up Redux-Loop almost as quickly as they would pick up Redux-Thunk. One major downside compared to Redux-Observable and Redux-Saga is, that Redux-Loop does not come with any additional helpers for cancellation, throttling or debouncing. So by default it is not quite as powerful as its major competitors.