Member-only story

Create a Global State object using React Hooks and Context API

Sze(‘Z’) Wong
2 min readOct 11, 2019

--

Luke Hall wrote about how to use React Hooks and Context API to create a system-wide state management object. I am not going to write about the background, you can read the detail from his post.

I am just going to write down how I end up using it in my projects.

STEP 1: Create globalStateContext.js

//As descriped in: export const initialState = {export const reducer = (state, update) => {export const StateContext = createContext();https://medium.com/simply/state-management-with-react-hooks-and-context-api-at-10-lines-of-code-baf6be8302c import React, {createContext, useContext, useReducer} from 'react';//Global States 
name: "swong",
email: "swong@zerionsoftware.com"
}; //This reducer takes any key/value pair and put into the global state object.
console.log("Set Global State "+JSON.stringify(update));
export const StateProvider = ({reducer, initialState, children}) =>(
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);

let newState = {...state, ...update}
return newState;
}; export const useGlobalState = () => useContext(StateContext);

STEP 2: Hook up the context in either index.js or app.js

import { initialState, reducer, StateProvider } from 'globalStateContext'

STEP 3: Use it ANYWHERE!

In any component inside your project, you can simply useGlobalState

--

--

Sze(‘Z’) Wong
Sze(‘Z’) Wong

Written by Sze(‘Z’) Wong

Serial entrepreneur, AI inventor, author and educator. CEO@Zerion Software, Co-founder@Zenith Venture Studio

No responses yet