lightweight-globalstate
v1.3.4
Published
An lightweight and easy state management hook for using React + Typescript
Downloads
6
Maintainers
Readme
Lightweight global state management for React + Typescript.
Setup
npm i lightweight-globalstate
import
StateProvider
from 'lightweight-globalstate';Wrap it around your application and optionally pass in a Type for your App state.
Optionally pass in an initial state
import React from 'react';
import { StateProvider } from 'lightweight-globalstate'; // 1. Import
const initialState = {
...whatever
}
const App: React.FC = () => {
return (
<StateProvider<T> initialState={initialState}> // 2. Wrap it up
{... your app}
</StateProvider>
);
};
export default App;
Access
The useGlobalState hook returns an array containing: your state object and an update function. eg.
import { useGlobalState } from 'lightweight-globalstate';
const [state,updateState] = useGlobalState<T>();
Update
- Call the updateState method
- Pass in an object containing the state you want to update
updateState({stateObject: newValue})
NOTE:
this works differently to React.useState(). updateState will not replace the state object. I will spread it into the existing state.
newState = {...state, ...newValue};