Coding for Global State

Explore some coding for a basic global state solution with React Hooks.

Building blocks for global state using Hooks

Discover what is needed to build the global state solution using useReducer and useContext:

  • Initial State
  • A reducer function
  • Global state object and the dispatch function
  • A Store Context with Provider

Initial State

The initial state can simply be defined as a JavaScript object. An example is shown below. A global state with the profile object, a greeting string, and a content array is provided.

const initialState = {
  profile: null,
  greeting: '',
  content: []
};

Reducer Function

A skeleton is shown below for a reducer that supports two action types: REFRESH_GREETING and REFRESH_PROFILE. Use this reducer with the useReducer hook.

const reducer = (state, action) => {
  switch (action.type) {
    case 'REFRESH_GREETING':
      // return updated state
    case 'REFRESH_PROFILE':
      return {
        // return updated state
      };
    default:
      return state;
  }
};

Global State object and Dispatch function

Using global state object and the dispatch function is as simple as calling useReducer with reducer and initialState.

const [globalState, dispatch] = useReducer(reducer, initialState);

A Store Context with Provider

Finally, you will need a Store. Define it as a context object so it can be accessed from any component.

An implementation that combines previous blocks using StoreContext is shown below. Create StoreContext by using the React.createContext. As seen earlier, you can use the useContext hook to access the value of the StoreContext object. In this case, the value will be set to an array containing globalState and dispatch.

export const StoreContext = React.createContext([]);

const App = () => {
  const [globalState, dispatch] = useReducer(reducer, initialState);
  return (
    <StoreContext.Provider value={[globalState, dispatch]}>
      {/* JSX to follow */}
    </StoreContext.Provider>
  );
};

Get hands-on with 1400+ tech skills courses.