Skip to content

Instantly share code, notes, and snippets.

@briandipalma
Last active June 11, 2019 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briandipalma/0233fdc47db15d41fd7a2124309afdc8 to your computer and use it in GitHub Desktop.
Save briandipalma/0233fdc47db15d41fd7a2124309afdc8 to your computer and use it in GitHub Desktop.
useReducer state becoming stale

When working with React components that have async data flowing into them either via single requests e.g. fetch calls or via a WebSocket connection/subscription state created with useReducer that is initially based on component props can become stale/incorrect as the data flows into the component and updates the props.

Also JSON.parseing data that flows in from a connection will create new objects even if the strings being parsed as the same each render. This can defeat useMemo and cause infinite rendering loops even if your useReducer reducer returns the same object on each call.

Returning null from a component triggers useEffect clean up code.

If in your action handlers you need to do more than just dispatch, like call a parent callback to provide a controlled value update then you can still use contexts to provide dispatch but you will just need to also passdown the parent callback/reducer required state that is provided by your parent. Overall it will result in fewer functions on your state and fewer props being passed down.

Instead of executing parent callbacks in the reducer try and return effect objects that describe what the component code should do next.

When you have a reducer dispatch that depends on state (A) that is created by a hook that depends on state created by the reducer create a new hook to deal with that dispatch processing (A) that is called after the hook creates the state (A).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment