React state management using context

Photo by Scott Evans on Unsplash

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.

  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'
});
// app.js<GlobalContext>
<App />
<GlobalContext
// myAwesomeComponent.jsimport {getContext} from 'smart-context'const MyAwesomeComponent = () => {
const {
state: { name },
actions: { setName },
} = React.useContext(getContext("myContext"));
}

--

--

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