How to useContext and useReducer in SharePoint Framework (SPFx)


React hooks are here for a while now, I was not getting a chance to explore React hooks in more detail especially in the context of SPFx.

Here are some very useful articles to read about the usage of React hooks in SPFx.

  1. Using React hooks to globally share service scope between components (by Vardhaman Deshpande)
  2. Using React hooks with service scope (by Garry Trinder)
  3. React Reusable Custom Hooks in SPFx (by Rabia William)

Summary

This is a simple web part which shows how to make use of useContext and useReducer hooks to retrieves contacts from the contact list and also updates a contact in the list using Fluent
UI panel control.

The main idea is to manage your app state globally using useReducer and access through useContext in your child components without passing through as component props

React hooks useReducer and useContext in SPFxReact hooks useReducer and useContext in SPFx

Implementation

Create an app context

First of all we need to create a global App context.

Create reducer

For simplicity, we are going to create a simple reducer with two actions

  1. GET_ALLITEMS
  2. SET_SELECTEDITEM

Root component

In our root component, first of all, we need to initialize our initial state and then pass this initial state to useReducer hook. The reducer will return an object containing state and dispatch.

The state will be our app state and dispatch method will be used to perform any action within our reducer.

Here we will also create our provider using our App Context created earlier (ListItemsContext). so that we can access our state and another service context globally.

ListItems component

This is how we are going to reterive latest state from reducer using useContext hook

👉 const { state, dispatch } = useContext(ListItemsContext);

This way, we can use the React useContext and useReducer hooks to globally share app state and other services context.

Hopefully, you have found this post helpful! All code is added in the GitHub repo here: https://github.com/ejazhussain/react-hooks-listitems


Author: Ejaz Hussain
Reprint policy: All articles in this blog are licensed under CC BY-SA 4.0 unless stating additionally.
  TOC