react-shared-query-state-2
v1.1.0
Published
A custom hooks that is derived from React.useState hook. This hook stores the state in the browser URL as search params. The state is shared across the application and sync to each other as long as the correct key is provided.
Downloads
6
Maintainers
Readme
React Shared Query State
A lightweight library for managing query state in React applications.
Features
- Easily manage and synchronize query state across multiple components.
- Simple API for setting, getting, and observing query state changes.
- Works seamlessly with React's component lifecycle and hooks.
Installation
Install the package using npm:
npm install react-shared-query-state-2
Install the package using yarn:
yarn add react-shared-query-state-2
Usage
import React from'react';
import { useSharedQueryParamState } from'react-shared-query-state-2';
const App = () => {
const [state, setState] = useSharedQueryParamState("state", 0);
return (
<div>
<h1>Query State: {state}</h1>
<button onClick={() => setState(state + 1)}>Increment</button>
</div>
);
}
export default App;
API
useSharedQueryParamState<T>(key:string, initialValue:T)
A custom hook for managing shared query state that is stored in URL query parameters.
Arguments
key
: The key to use for storing and retrieving the query state. This key should be unique to your application.initialValue
: The initial value to use for the query state.
Returns
state
T: The current value of the query state.setState
React.Dispatch<React.SetStateAction>: A function for setting the value of the query state. This function accepts a single argument, which is the new value to set.
useLocalStorage<T>(key:string, initialValue:T)
A custom hook for managing shared query state that is store in localStorage.
Arguments
key
: The key to use for storing and retrieving the query state. This key should be unique to your application.initialValue
: The initial value to use for the query state.
Returns
state
T: The current value of the query state. This key should be unique to your application.setState
(value: T) => void: A function for setting the value of the query state.
useBroadcastChannel<T>(channelName: string)
A custom hook wrapping the BroadcastChannel API.
Arguments
channelName
: The name of the channel to use for broadcasting messages.
Returns
{
message
: T | null,
postMessage
: (message: T) => void,
}