@anupamshandilya28/selective-context
v0.1.0
Published
A fast and lightweight React context state management library
Maintainers
Readme
Selective Context
A fast and lightweight state management library for React using Context API.
Installation
npm install @anupamshandilya28/selective-context
# or
yarn add @anupamshandilya28/selective-contextFeatures
- Lightweight and minimalistic API
- TypeScript support
- Fast updates with selective re-rendering
- Built-in Snackbar notifications
- Zero dependencies
Usage
1. Create a store
// store.ts
import { createFastContext } from '@anupamshandilya28/selective-context';
type StoreType = {
count: number;
user: {
name: string;
isLoggedIn: boolean;
};
};
const initialState: StoreType = {
count: 0,
user: {
name: '',
isLoggedIn: false,
},
};
export const { Provider, useStore } = createFastContext(initialState);2. Wrap your application with the Provider
// App.tsx
import React from 'react';
import { Provider } from './store';
import Counter from './Counter';
import UserInfo from './UserInfo';
function App() {
return (
<Provider>
<h1>Fast Context Demo</h1>
<Counter />
<UserInfo />
</Provider>
);
}
export default App;3. Use the store in your components
// Counter.tsx
import React from 'react';
import { useStore } from './store';
import { useSnackbar } from '@anupamshandilya28/selective-context';
function Counter() {
const [count, setStore] = useStore(state => state.count);
const { showSnackbar } = useSnackbar();
const increment = () => {
setStore(state => ({ count: state.count + 1 }));
showSnackbar('Counter incremented!', 'success');
};
const decrement = () => {
setStore(state => ({ count: state.count - 1 }));
showSnackbar('Counter decremented!', 'info');
};
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;Using the Snackbar
The package includes a built-in Snackbar system for notifications:
import { useSnackbar } from '@anupamshandilya28/selective-context';
function MyComponent() {
const { showSnackbar } = useSnackbar();
const handleClick = () => {
// Show different types of notifications
showSnackbar('Operation successful!', 'success');
// Other options: 'error', 'info', 'warning'
};
return <button onClick={handleClick}>Show Notification</button>;
}API Reference
createFastContext(initialState)
Creates a new context with the provided initial state.
Returns:
Provider: React component to wrap your applicationuseStore: Hook to access and update the store
useStore(selector)
Hook to select and subscribe to parts of the store.
Parameters:
selector: Function that selects a part of the store
Returns:
[selectedState, setStore]: Array containing the selected state and a setter function
useSnackbar()
Hook to access the snackbar functionality.
Returns:
showSnackbar(message, severity): Function to show a notificationhideSnackbar(): Function to hide the current notification
License
MIT
