DEV Community

souvik
souvik

Posted on

State management in React made easy

If you are using react to build web apps, you would know managing state is fairly complex, you either have to use big state management libraries like redux or use context api. Both approaches needs you to write a lot of boilerplate code, even to work on a small and easy to build feature.

I faced a lot of these problems, thus I created this util library called kladi. It is built using context api. Using kladi is fairly simple.

Here is how easy it is to use

  • First, install kladi by typing npm i kladi
  • Then you need to wrap your base component with a provider so that all components in your component tree gets the global state.

import { Provider } from "kladi";

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
  <Provider initialState={{count: 0}}>
    <App />
  </Provider>,
  document.getElementById("root")
);

you can pass an initial state object for you access anywhere in the component tree.

  • Now to access your state anywhere from the component tree use the hook provided by kladi
import {useState} from "kladi"

const app = props => {

const [count, setCount] = useState('count')
const [name, setName] = useState('name', "Kladi")

return <>
{count} 
<button onClick={() => {setCount(count + 1)}}>Press</button>
{name}
</>
}

  • yes you can create a new state in the fly and also access them in other components as well. Well, it does look like the useState hook from react, but this state is global.

  • To create and access state you need to maintain a unique string value.
    also to create a new state, you have to provide a default value, but if you are accessing a state that is already present then you don't need to provide the default value.


This library is new and under development, if you use this library and found any bugs pls create an issue here.

Top comments (0)