State management - GRIM-Technologies/react-training.adv GitHub Wiki

The state management and prop drilling problem can be seen in the repository's "state" section.

The Problem

We have a 5-level component hierarchy where:

  • Top component (AccountDashboard) manages user state
  • Bottom component (EmailToggle) needs to use that state
  • 3 middle components just pass props through without using them

Component Structure

AccountDashboard (has state)
└── AccountSettingsPanel (passes props)
    └── SettingsContainer (passes props)
        └── NotificationPreferences (passes props)
            └── EmailToggle (uses props)

Task #1

Choose an approach to eliminate prop drilling.

  • Context API - Built-in React solution
  • Redux - Popular external library
  • Zustand - Lightweight alternative
  • Other - Or choose your own tool!

Task #2

If you are accustomed to Redux and want to explore solutions to more complex problems like side-effects and handling of some of the following cruxes, then feel free to checkout the branch with-redux where Redux has already been implemented, and you can focus on the side-effects part.

  • Compound workflows
  • Request throttling
  • Background polling
  • Cancellation of effects

Example 1

Imagine a user wants to transfer money from their savings account to their checking account. This process may involve multiple steps that need to be executed in a specific order (compound workflow):

  • Authenticate the User: Check if the user has the necessary permissions.
  • Validate the Transaction: Ensure that the transfer amount is valid and that there are sufficient funds.
  • Execute the Transfer: Move funds between accounts.
  • Notify the User: Send a confirmation message to the user.

Depending on the result of these steps, we may need to branch our workflow and invoke different workflows. Redux Saga is particularly good at handling these kinds of side effects.

Task #3

Using redux-saga, implement the following scenario.

  • A button in the UI is clicked
  • An action is dispatched "post/update", with some optional payload
  • Build out a saga side effect watcher and worker to handle this action
    • The worker should make an API call (PUT) to '/posts/1'
  • Ensure, using redux-saga, that subsequent actions of the same type ("post/update") are throttled, so that only 1 update call per 5 seconds happens

Fetch example:

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PUT',
  body: JSON.stringify({
    id: 1,
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})