React state management using context

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

Photo by Scott Evans on Unsplash

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!✌️

--

--

Web Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store