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

State Management with React Context API

State Management with React Context API

Vivek Nayyar

July 02, 2018
Tweet

More Decks by Vivek Nayyar

Other Decks in Education

Transcript

  1. About me My name is Vivek Nayyar I work as

    an UI Engineer with Trusting Social. ex hotstar and housing. Follow me @viveknayyar09
  2. Problem - Every component has to pass the currency prop(Prop

    Drilling) PhysialCo muting HTML, CSS,JS
  3. Problem:- We will need to send the data 10 from

    the Red component to the Blue one just to be able to send it to the Green one
  4. React Context API — What is it? Context provides a way to

    pass data through the component tree without having to pass props down manually at every level.
  5. How to use this new version of Context? • React.createContext

    is passed the initial value. It returns an object with a Provider and a Consumer. • The Provider component is used higher in the tree and accepts a prop called value. This value can be anything! • The Consumer component is used anywhere below the Provider in the tree and accepts a prop called children and must be a function that can accept a value and return a JSX.
  6. Basic Flux Representation - Store is a single global source

    of truth. - Action are functions to call api endpoints and get the new data. - Dispatcher is used to dispatch the action to reducers which in turn update the store and the ui re-renders.
  7. Implementation With the createContext() API example above, we already have

    the unidirectional Store → View in place. const Context = createContext()
  8. What we need is actions and dispatchers to dynamically update

    the store. What if our dynamic store was just the state of a root React component?
  9. Caveats Because context uses reference identity to determine when to

    re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider’s parent re-renders. For example, the code above will re-render all consumers every time the Provider re-renders because a new object is always created for value:
  10. Better Way - To get around this, lift the store

    value needed into the parent’s state. - Lift value inside this.value - Re-render only if this.state is not equal to this.value.state
  11. Existing state management libraries which are using new React 16.3

    Context API • Unstated (https://github.com/jamiebuilds/unstated) • React-waterfall (https://github.com/didierfranc/react-waterfall) • Constate (https://github.com/diegohaz/constate) • React-restated (https://github.com/rajeshpillai/react-restated)