State Management in React

Due Tue 4/29 midnight, late by class time on Thu 5/1.

Assignment (in-progress)

https://classroom.github.com/a/XADOZ40A
  • clone the repository for the work-in-class example
  • copy your A11 project (client and server) from the last assignment over
  • test that it still works

In this assignment, we will refactor our react scheduler app to use a centralized state management library. Global state management with Redux has long been considered necessary for react apps with any level of complex state. Managing state per-component gets too unwieldy otherwise.

As is always the case, as developers have settled into predictable usage patterns, newer libraries have come along to streamline or otherwise improve on the ideas. We'll be using zustand, a very popular option that sells itself on being small and fast with far less boilerplate compared to Redux.

The Steps

Again, make sure that your A11 is working *before* you start changing anything.

The steps below include images from the class_example that we went through together, to indicate which part of the example maps to which step in the assignment.

npm install zustand

The store and top-level component

  • Create store.js to hold all our state (courses, instructors, loading, error)

  • Don't forget to default export the useStore function and import it into App.jsx
  • Add the initial fetch action to the store (include error handling)

  • Use selective subscription in App to run the fetch action and display the data

Sub components

  • Subcomponent data (e.g. courses, sections) can be passed in via props or subscribed to (by id) from inside the component
  • With simple, already nested data, props still make sense here
  • Since we've chosen to pass the course object as a prop, we don't subscribe to it
    • The Course will already be redrawn when the courses data changes and triggers a redraw of App
  • Add the addSection action to the store and subscribe to it from Course
    • In your handler, use the set function that is passed into create to do store updates

    • set passes the store into your callback, but if you need access to the store outside set, you can use the getStore parameter passed to create

  • memo the Course component to avoid unnecessary redraws

Finishing it up

  • Repeat for your Section component and its edit and delete actions
  • Do not memo the Section (simple pass-through component and it's parent is already memoized)
  • Finish with the add course action