Global state management

Global state management

In this presentation, we explore the state management problem that we have using only local state, how this problem can be solved by using global state management library (Redux & Rematch), as well some of the important concepts from functional programming crucial for understanding and using Redux.

800c1a87c30c83ccc214e220b09e4def?s=128

Konstantin

March 27, 2019
Tweet

Transcript

  1. GLOBAL STATE MANAGEMENT Konstantin Lebedev

  2. LOCAL STATE !2

  3. !3

  4. !4

  5. !5

  6. !6

  7. !7

  8. !8

  9. WHAT SHOULD BE IN GLOBAL STATE? !9

  10. !10 “Should more than one component re-render if the state

    changes?“ Million-dollar question
  11. WHAT TO PUT INTO GLOBAL STATE DO PUT ✅ Session

    data ✅ Same data that has different representation in different components ✅ Data that you want to cache / make available offline DON'T PUT ❌ UI component state (is dropdown open?) ❌ Loading state (isLoading, isCreating, isUpdating, etc..) ❌ Form values Use these as guidelines, not as rules. !11
  12. IMMUTABILITY !12

  13. WHAT IS IMMUTABILITY? • Immutable variable is a variable that

    once initialized, cannot be changed • To update its value, we create a new variable !13
  14. WHY IMMUTABILITY? • Makes your code predictable • Easier to

    test • Helps with render optimization !14
  15. PURE FUNCTIONS !15

  16. PURE FUNCTIONS • Given the same input, always return the

    same output • Don’t change their arguments • Have no side-effects (don’t reference any external resources - API, localStorage, etc.) !16
  17. QUIZ TIME! !17

  18. PURE OR NOT? !18

  19. PURE OR NOT? !19

  20. PURE OR NOT? !20

  21. PURE OR NOT? !21

  22. PURE OR NOT? !22

  23. REDUX !23

  24. WHAT’S REDUX? • Predictable state container • Based on 3

    main principles (3 pillars of Redux) !24
  25. #1: STATE IS A READONLY JS OBJECT !25

  26. #2: TO CHANGE STATE, WE DISPATCH AN ACTION !26

  27. #3: REDUCERS: CURRENT STATE + ACTION -> NEXT STATE !27

  28. REDUX !28

  29. DESIGNING STATE SHAPE • Keep it as flat as possible

    • Have top-level properties as “models” • Deduplicate/normalize data • Think of global state as client-side DB !29
  30. BEYOND REDUX !30

  31. REDUX PROBLEMS • Ton of boilerplate • Lack of built-in

    support for side-effects !31
  32. REMATCH !32

  33. REMATCH !33

  34. RESOURCES • Redux repo: https://github.com/reduxjs/redux • Learning Redux: https://redux.js.org/introduction/getting-started •

    Rematch repo: https://github.com/rematch/rematch !34
  35. SUMMARY • State management problem • Global state vs. local

    • Immutability and purity • Redux !35
  36. THAT'S IT Konstantin Lebedev konstantin.lebedev@strv.com