React state management using context

Achal Jain
2 min readDec 28, 2020

--

Introducing ‘smart-context’, a quick and light-weight state management solution for React applications.

Photo by Scott Evans on Unsplash

Efficient state management is one of the main concerns for any application architecture. While the power of state management libraries might be a great idea for large applications with lot of files and shared data, it can be quite a work for small to mid-size applications considering the learning curve, configuration, setup, the web of import statements and what not!

It is always a good idea to find smart ways to get the job done with existing tools and techniques. The obvious immediate benefits are, no learning curve, no complex setup.

smart-context

smart-context is an npm package developed to solve the same problem for React applications. As the name suggests, it relies on React’s in-built Context API and useReducer hook to provide a quick and lightweight state management solution. It keeps the source code neat and organized. It makes the global state easy to maintain and scale.

The package is very simple to use with just two functions:

  1. initContext: one-time setup with an initial state, a list of actions, a good name
  2. getContext: access the context (state, actions)

Usage

initContext will return a context provider wrapper.

// setup.jsimport {initContext} from 'smart-context' const GlobalContext = initContext({
initialState: { name: '' },
actionsConfig: { setName: ['name'] },
displayName: 'myContext'
});

Put your App inside the context wrapper.

// app.js<GlobalContext>
<App />
<GlobalContext

Access state and actions via the getContext function.

// myAwesomeComponent.jsimport {getContext} from 'smart-context'const MyAwesomeComponent = () => {
const {
state: { name },
actions: { setName },
} = React.useContext(getContext("myContext"));
}

The best part, use as many contexts as you want! Multiple stores are supported out of the box with no extra setup.

Refer to Github for complete example and documentation.

Happy coding!✌️

--

--