Redux Flashcards
What will we learn?
everything we need to know to build real, complex apps with Redux
work on a real bug tracking app with a node backend
by end of course, know and understand Redux inside/out
What is Redux?
A state management library for Javascript applications
doesn’t care what library we use for UI development
instead of scattering app state across UI
store state in a single JS object (store)
single source of truth
like a “database” for front end
components get state from store
data is updated in a single place
can see how data changed, why, when and where it came from
Why do we need redux (state managment)?
complex UI, need to keep in sync
data updates from backend request, user interaction, etc. changes must be reflected immediately
What are the pro’s of Redux?
debugging
transparent state changes
can reload state, view actions and see UI changes
cache/preserve page state
entire app state available on client in JS object (store)
don’t have to reload data from server
centralized state
data is available in one place, accessible by all parts of UI
When is redux NOT right for my project?
must consider constraints and problem domain
A real software engineer is an active problem solver
not every application requires Redux
DON’T USE
if load data and display statically (not changing)
if it’s a tight budget
if the UI is very simple
**it will be complex and slow you downl
What is functional programming?
Redux is built on top of functional programming
A good background is critical to building redux apps
One of the programming paradigms
Each paradigm has rules for how to structure code to solve problems
invented in 1950s
decomposing a problem into small, re-usable functions
can compose functions to build complex pipelines
Pros
can run in parrallel
exploit multiple cores
Benefits:
more concise
easier to debug
easier to test
more scalable
Why are functions first class citizens in Javascript?
can treat them like any other variables
assign them as variables
pass them as arguments
return them from other functions
What are higher order functions?
a function that…
takes a function as an argument
returns a function
both!
Why?
instead of working on strings, numbers or booleans
it goes higher to operates on functions
What is the problem with this approach?
expression is read right to left
trim, make lowercase, wrap in div
so many parenthesis
Soln?
What is currying?
Solves this problem:
functional pipeline
function in line requires two parameters (fns)
only have one fn as parameter
How?
allows us to take a fn with N arguments
convert it to an fn with 1 argument
What?
instead of separating args with commas “,”
separate with ( )
What is the challenge with this code?
wrap function expects two arguments
if we pass type as argument
pipeline will throw an error
Why?
it requires a function as argument, not string
Soln?
currying
What are pure functions?
a function that given the same args, produces the same result
NOT:
random values
current date/time
global state
Why?
These change
Redux?
reducers must be pure
other fns don’t have to be
What are the benefits of pure functions?
Self documenting
everything a fn needs is clearly identified in parameter signature
easier to test
no global state
concurrency
because not using global state
can run in parallel
cacheable
can store result in cache and use in future
useful in programs with intensive computations
if we know certain computations produce same results
can optimize by storing in a cache
What is immutability?
Goes hand in hand with pure functions
once we create an object, cannot be changed
must take a copy and change that copy
Ex. Strings are immutable, create copy, original string not affected
Objects and arrays can be modified directly, not immutable
Does “const” prevent mutability?
No
it prevents re-assignment
common misconception
Ex. cannot re-assign book to another object
What are the benefits of immutability?
Predicatable apps
if we call a fn, pass an obj
obj won’t get changed, no suprises down road
Fast change detection
React needs to know when changed
creating a new obj, stored in memory
React compares objects by references
this is fast operation
in contrast, without immutability
React has to compare all properties in two objects to see it’s changed
slow operation
Concurrency
can run in parallel
not going to affect something that affects system as a whole
What is the problem with this code?
Spread operator does a shallow copy
nested objects are copied by reference (not value)
Ex. Both person2 and person2copy have the same reference to “address” in memory (not copied by value) copied by reference
Soln?
Do a deep copy
set a new nested object using spread operator
How do we copy an array and insert a number at a specific location?
How do we update an array using immutability?
Hint:.map ( ) method
How do we enforce immutability?
By default, Javascript doesn’t do this
Why?
It’s a multi paradigm language
it doesn’t enforce immutability without libraries
Soln?
Libraries that enforce real immutability
Different people love different tools
Immutable.js (by Facebook)
Immer (becoming trendy, Mosh loves it)
What is immutable.js?
Hint: npm i immutable
a library by Facebook
provides a bunch of immutable data structures
*Mosh prefer’s another library
How?
instead of a plan JS object
use one of the datastructures from this library
Problems?
have to learn a new API
cannot access obj properties with . or [] notation
have to use .get( ) method
integration with other libraries
hard to integrate with other libraries that expect plain JS objects
have to call .toJS( ) method to convert to plain JS objects
What is Immer?
Hint: Immutability library (npm i immer)
almost as popular as immutable.js
Pros
writing code as if mutating objects but actually not
better than using spread operator (get’s nasty with nested objs)
Write code to solve this?
Hint: function composition
What are the three building blocks in Redux applications?
Store
single JS Object that includes application state
Actions
plain JS Objects that represent what happened
aka events (what happened)
Reducers
one or more functions responsible for updating a slice of Store (single JS object)
aka event handlers or processors
pure functions, don’t mutate arguments, no side effects
How do Redux building blocks work together?
Action object is dispatched to Store
Store calles the Reducer
Ex. When user performs an action (add item to shopping cart)
Create an Action item and dispatch it
Store object has dispatch method that takes an action
Store object forwards action to reducer
Reducer is not called directly, we only work with the Store
Store is in charge of calling the reducer
Reducer computes new state and returns it to Store
Store sets state internally and notifies UI components directly
Write code to solve this?
Hint: immutabile objects / arrays
What is a store?
simple API interface
JS Object
includes properties:
.dispatch
method for dispatching actions
.subscribe
method for subscribing to store
get notified everytime state of store changes
used by UI layer
.getState
get current state of store
to change state of store, have to dispatch an action
Store object has dispatch method that takes an action
Store object forwards action to reducer
Reducer is not called directly, we only work with the Store
Store is in charge of calling the reducer
Reducer computes new state and returns it to Store
Store sets state internally and notifies UI components directly
What is a reducer?
A function that takes current instance of the store (JS state object) and returns an updated store
Returns?
using spread operator or immutable library to return an updated store
How?
supply store and an action as arguments
action is a plain JS object describing what just happened
lets reducer know what to update in store (JS state object)
Many?
each reducer is responsible for updating a specific part of the store
Ex. Many departments in a store, each department has a manager
What is an action?
argument to the reducer function
tells reducer what properties in store to update
actions that happen in our applications (events)
Ex. UserLogin, UserLogout
based on the type of action, reduce will know what parts of store (state) to update
Why is redux designed this way (ie. to dispatch actions)?
Dispatch is like entry point to store (JS state object)
every action is sent through same entry point
central place to control what should happen every time a user performs an action
can log every action
can implement undue/redue mechanism
What are the four steps to follow when building a redux app?
Design the Store
What do you want keep in the store?
Define Actions
What are actions user can perform in application?
Create Reducers
Take an action, return updated state
Setup Store based on Reducer
How would we design the store of a real world application for tracking bugs?
An object with two properties (slices):
bugs - list of bugs
current user - initially null, then set when user login
*two slices, requires two reducers
What actions would a user perform in a real bug tracking application?
An action is just a plain JS object that describes what happened
must have a type property (required)
Payload property contains minimum data including description or ID for an action
description can be any serializeable data type
because description must be able to store on disk, reload later
use strings so we can view description of what happend
can store form data in description, etc. (bug type, who logged, etc)
ADD_BUG
bugAdded
common conventions for type in Redux apps
(vs. numberss not descriptive)
Actions (events):
Add a bug
Change status of bug
filter list of bugs
change sort order
Mark as resolved
Delete a bug
How do we create a reducer?
What’s the problem with this code?
In real app
payload contains minimum required information
Ex. bugAdded -> only need ID, not description too
Use immutable library in real app (not spread operator)
How do we implement this logic using switch and case?
Reducer is a pure function
everything it needs is passed as arguments (only dependencies)
given the same input, returns same output
doesn’t touch DOM elements
doesn’t work with global state
No API calls
How do we create a store?
Hint: single JS object that contains app state
import {createStore} from ‘redux’;
import reducer from ’./reducer’;
How do we create a store?
How do we dispatch an action?
In real app,
when user clicks add button
we are going to dispatch an action (raise an event)
How do we subscribe to the store?
Hint: get current state of store everytime state changes
store.subscribe ( )
takes a fn
called everytime a change happens in the UI
UI components should subscribe to store so they are notified when changes happen
What does the subscribe method return?
a fn for unsubscribing from store
possible user navigates away from current page
in new page, don’t have UI component
don’t want to be subscribed to a UI component that is not visable
this can create memory leaks
What is the redux workflow?
Hint: code example
When we dispatch an action
store.dispatch( { action } )
store calls reducer
state = reducer (state = [] , action)
store gives reducer current state in store and action passed to store
reducer returns a new state to store
based on logic / type of action (switch case)
notifies subscribers of changed state
What’s the problem with this code?
we hard coded the action type (string)
if we change the action type name later
will have to change in multiple places or get a bug
Soln?
create a file actionTypes.js
What’s the problem with this implementation?
dispatching an action is not easy
have to type the entire structure
if re-using action in multiple places, will duplicate code
Soln?
Create a fn that creates action object
How do we implement BUG_RESOLVED?
Create the action first
plan JS object w/ type + payload
store.dispatch ( action )
Create the reducer next
returns an updated state object to store
store.subscribe ( observer ) notifies observers of state change
Pass action to store
store.dispatch ( action )
What is a good idea when learning a new tool?
Think about how that tool works and how it was built
Mosh is going to show us how Redux works / is built!
We are going to build Redux from scratch
How do we build the store from scratch?
state property is a private property
How do we create a private property?
How do we implement the dispatch method in our custom store?
Call the reducer to get the new state
Notify the subscribers
How do we implement the subscribe method from scratch?
How do we use Redux Dev Tools?
Hint: A powerful tool for debugging redux applications
We need to pass extension to createStore ( ) method
Add:
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
A powerful tool for debugging redux applications
What is the log monitor?
Hint: Redux Dev Tools
a plain list of actions that have been applied
Action + state after action applied
What is the Chart field?
Hint: Redux Dev tools
show actions in a visual way
Ex. DollarShaveClub’s React/Redux Actions Chart
What is the inspector field?
Hint: Redux Dev tools
diff shows you how tab has changed
How can I identify the source of problem in my Redux app?
using Redux Dev Tools:
1. Look at actions dispatch - ensure right action was dispatched, if not dispatch that action
- Check to ensure action was carrying the right data, if not modify action creator (responsible for action)
3. Check state tab - ensure state was updated properly, if not modify reducer function (responsible for state)
What is the test tab?
Hint: Redux Dev Tools
Generates basic boiler plate for testing action