wheza-state
v1.2.2
Published
A lightweight state management library for React Native, built on the singleton pattern with namespace support.
Downloads
13
Readme
Wheza-State
A lightweight state management library for React Native, built on the singleton pattern with namespace support.
Wheza-State is a lightweight state management library for React Native that uses the singleton pattern to provide a global point of access to your application's state. With namespace support, you can organize your state into separate scopes and manage different types of state, its provides a simple and effective way to manage your state and keep your code organized.
Overview
Wheza-State allows you to manage your application's state in a modular and organized way, using namespaces to categorize and structure your data. This approach enables you to define namespaces for different aspects of your application, such as:
- API responses
- System-wide settings
- Alerts and loading states
- Page-specific data (e.g., tabs)
Getting Started
To integrate Wheza-State into your project:
- Install Wheza-State into your project.
npm i wheza-state- Import Wheza-State using the standard ES6 import syntax:
import wstate from 'wheza-state';Example Usage
Here are a couple of examples demonstrating how to use Wheza-State in a real-world scenario:
Initial wstate for Login
import wstate from 'wheza-state';
wstate.updateState('app.system.auth', {
isLoading: 'Loading...',
access_token: null,
user: null,
});
export function RootLayout() {
...
return (<>...</>);
}In this example, we're initializing the Wheza-State with an initial state for the app.system.auth namespace. This sets the initial values for the isLoading, access_token, and user properties.
extracted for clarity
in other project I find it more clear to get it out into a file:
import wstate from 'wheza-state';
export function beforeReactLifecycle() {
wstate.updateState('app.system.flag', {
message: 'Loading...',
apicall: 0,
route: [],
});
wstate.updateState('app.system.auth', {
access_token: null,
user: null,
cred: {
identifier: "",
password: ""
}
});
}Link Rerender to Namespace
import { useState } from "react";
import wstate from 'wheza-state';
export function TabLayout() {
const [, rerender] = useState();
const state = wstate.getState('app.system.auth', {TabLayout:rerender});
return (<>...</>);
}In this example, we're linking the rerender of the TabLayout component to the app.system.auth namespace. Whenever the state of this namespace changes, the component will automatically rerender with the new state.
make use(*) helpers
Part of implementation details is to link namespace with rerender, with these helper, rerender will be internally defined:
{getState, rerender} = useRerender(namespace, rerenderName){getState, rerender, state} = useGetState(namespace, rerenderName)
useGetState
import { useGetState } from 'wheza-state/use'
export function TabLayout() {
const {state} = useGetState('app.system.auth', 'TabLayout');
return (<>...</>);
}useRerender
useRerender will return getStatefunc which will use same rerender defined in params of useRerender
export default function Login() {
const {getState} = useRerender('app.system.flag', 'Login');
const sysState = getState('app.system.auth');
if (sysState.redirect) {
return <Redirect href={sysState.redirect} />;
}
return (<>
<AppbarBack/>
<BSkyLoginPage />
<Loading />
</>
);
}Google OAuth Login
import wstate from 'wheza-state';
export function GoogleOAuthLogin(props:any) {
let state = wstate.getState('app.system.auth');
if (state.isLoading) {
return (<Loading state={state}/>);
}
if (state.user) {
return <Redirect href="(tabs)" />;
}
return (<GoogleOAuthButton state={state} auth={auth}/ >);
}In this example, we're using Wheza-State to manage the authentication state of the application. We're checking if the user is currently loading, and if so, we're displaying a loading indicator. If the user is already authenticated, we're redirecting them to the tabs section of the application.
Home Screen with Logout Functionality
import wstate from 'wheza-state';
export function HomeScreen() {
let state = wstate.getState('app.system.auth');
const logout = async () => {
await removeToken('access_token');
state = state.getState();
state.access_token = null;
state.isLoading = false;
state.user = null;
state.update();
}
return (
<ScrollView>
<Button mode="contained" onPress={logout}>Logout</Button>
</ScrollView>
);
}In this example, we're using Wheza-State to manage the authentication state of the application. We're also implementing a logout functionality, where the user can press a logout button to remove their access token, update the authentication state, and refresh the state using the update() method.
Development Mode
When running in development mode (__DEV__ === true), the library provides additional debugging capabilities:
- Exposes
currentStateon the window object for state inspection - Exposes
rerenderMapon the window object for tracking re-renders
Bundler Configuration
The library uses build-time constants for development mode detection. To properly configure this in your project:
Using Metro (React Native)
In React Native, __DEV__ is automatically provided by the environment. You can control it through the --dev flag when bundling:
# Development build (sets __DEV__ = true)
react-native bundle --platform ios --dev true --entry-file index.js --bundle-output ios/main.jsbundle
# Production build (sets __DEV__ = false)
react-native bundle --platform ios --dev false --entry-file index.js --bundle-output ios/main.jsbundleMetro will automatically handle tree-shaking of development-only code when --dev false is used.
Using Webpack (Web)
// webpack.config.js
module.exports = {
// ...
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(process.env.NODE_ENV !== 'production')
})
]
}These configurations ensure that development-only code is properly stripped out in production builds, optimizing your bundle size.
Acknowledgment
Wheza-State was extracted from a personal project and is now being shared as open-source, with the hope that others will find it useful.
License
Wheza-State is licensed under the MIT License.
Copyright (c) 2024 Widi Harsojo
Contributing
Contributions are welcome! If you'd like to report a bug, suggest a feature, or submit a pull request, please feel free to do so.
