Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Advanced Redux - Tonida Baraza

Advanced Redux - Tonida Baraza

Avatar for Developer Circles: Nairobi

Developer Circles: Nairobi

August 04, 2017
Tweet

More Decks by Developer Circles: Nairobi

Other Decks in Programming

Transcript

  1. Why Redux Is it the best choice? - Most popular

    close to 30k stars - More features and stars than flux or relay - Easy to introduce redux on large -scale projects https://github.com/tbaraza/redux-pres Advanced-redux branch
  2. Immutability - In js Objects and arrays are not immutable

    by default - string and numbers are - Using const keyword - Object.freeze() to make an object immutable but this doesn’t work on nested objects - Deep-freeze, Immutable.JS - State is represented as an object - … spread operator used to create copy - https://medium.com/@dtinth/immutable-js-persistent-data-structures-and-structural-sharing-6d163f bd73d2
  3. Immutable.js - Wraps mutable objects in immutable maps. - Maps

    have API for changing data - Data is never mutated but copied - Faster than using spread operator which is simple - E.g const a = [ “a”, “b”, “c” ] - Const b = List(a) - Const c = set(2, “d”) - https://facebook.github.io/immutable-js/
  4. Advantages of using Immutable.js - History state is preserved -

    Faster performance - large - Specific commands to make changes - changes are deliberate - Prevent errors from creeping into code base e.g object referred by a service is modified by another service - Community support
  5. Disadvantages of Immutable js - Prone to silent failure. Dot

    notation - Nested objects are a challenge to modify - Syntax can be unfamiliar - Immutable objects do not work for services that require a regular objects e.g combinedReducers - Spread or rest operators may not work with immutable objects. This depends on the version of Immutable js you are using
  6. State shape State can be structured as normalized or denormalized

    - Normalized i.e Data is never repeated - Denormalized i.e Each entry contains the references it needs - Objects are denormalized shape - Updating state is harder when data is repeated - Updates can trigger unnecessary redraws - Reducers are not dry and too complex if denormalized
  7. Default Redux State with Immutable js - Implement normalized state

    shape - Convert plain Javascript object to Map with fromJS utility
  8. CombineReducers This is a redux utility that allows you to

    update the state tree by allocating a reducer to a slice of state. This reducer will be responsible for updating the slice of state specified for the reducer. Why would you need this: - App gets more complex How does it work - Takes in different reducer functions and returns a single reducer that you pass to createStore. - The resulting reducer calls every child reducer and gathers their results into a single state object.
  9. CombineReducer best practices - For any action not recognized, it

    must return state given to it as the first argument. - It must never return undefined. - If state given to it is undefined, it must return initial state for the specific reducer - Refer to one of the redux modules: count or signup
  10. Implementation - We have two reducers: count and auth. -

    The resulting state tree will contain the following:
  11. CombineReducers Limitations and Advs of inbuilt CombineReducers Advantages - Enforces

    best practises - Simple and easy to understand - Already familiar to most developers - Suitable for simple projects, prototypes Disadvantages - Single reducer can’t work on multiple parts of the state - Does not work on non-object states - Does not work with immutable.js-based states - Not suitable for very large projects
  12. Beyond CombineReducers Other use cases that inbuilt combineReducer can’t handle

    as described in docs http://redux.js.org/docs/recipes/reducers/BeyondCombineReducers.html - Using slice reducers with Immutable.js objects - Suggestion: redux-immutable - Sharing data between slice reducers - Suggestion: Create custom function to pass the needed data as arguments to the reducer - Put more data into an action - Ordering of slice reducer calls - Check out Redux Addons Catalog - Write your own custom function that solves your case
  13. Redux Middleware It provides a third-party extension point between dispatching

    an action, and the moment it reaches the reducer. Why Use them: - Manages the side effects - Pre-process actions - Track and debug an application - Keep special logic out of action creators - Isolate API communications
  14. Popular Redux Middleware Common Middlewares - Redux Thunk - Enable

    you to create action creators that return a function instead of an action i.e object - Redux Saga - Runs asynchronous processes - Redux Promise - Allows Promises to be passed to dispatcher - Redux Logger - Log actions to console - Redux Reporter - Report activities to 3rd parties - Redux Undo - Revert to previous states
  15. Redux Thunk A thunk is a function that delays evaluation

    of code; i.e the function has to be invoked. In Redux thunk can be used to: - delay the dispatch of an action or dispatch once a condition is met. - Allow action creators to return a function instead of an object - Preprocess state Takes Dispatch and getState as arguments An example of thunk is selectors https://github.com/gaearon/redux-thunk
  16. Selectors A selector is a method that takes in state

    as an argument and returns a property of the state.
  17. Advanced Selectors You can use the reselect library to: -

    Compose selectors - Cache selectors state
  18. Redux Saga Saga is a long running process. Initialises at

    beginning of your application and continuously waits for events and actions. This is a middleware that manages side effects Responds to actions in the either of the following ways: - Dispatching new action with results - Side effects. E.g calling an external API Uses yield keyword - used in generator functions https://redux-saga.js.org/
  19. How it works - Initialize middleware - Saga middleware is

    passed a bundle of sagas which are then initialized - Middleware which has saga is added to store - Whenever an action is dispatched it is passed via middleware to the saga - The saga then executes - The process repeats indefinitely
  20. Redux saga vs Redux Thunk Redux Saga Redux Thunk -

    Middleware - Middleware - Requires compilation - Not necessary - Creates side-effects - Unless implemented inside thunks - Suitable for asynchronous calls - Suitable for synchronous calls
  21. Implementing Sagas - Install redux-saga and implement it - Create

    a saga that listens to updates and actions - Connect the saga to applications events - Use saga to create side-effects