UNPKG

@d3vtool/hooks

Version:

Collection of custom React hooks to simplify tasks in your React projects.

33 lines (32 loc) 1.88 kB
export type InitializerAction<T> = () => T; export type NewMStateAction<T> = (mostRecentSnapshot: T) => void; export type SetMStateAction<T> = (newStateAction: NewMStateAction<T>, deepClone?: boolean) => void; export type UseMState<T> = [T, SetMStateAction<T>]; /** * A custom hook that provides a stateful mutable value and a function to update it. * * This hook is designed to mimic the functionality of React's `useState`, providing a way to manage state within a component in a mutable way. * It can either be initialized with a direct value or with an initializer function (action) that computes the initial state value. * It returns the current state value and a function to update it. * * @param initialState - The initial value for the state, or a function (initializer) that returns the initial state. * - If a value is passed, it will be used as the initial state. * - If a function is passed, the function will be invoked to generate the initial state. * * @returns An array with two elements: * 1. The current state value (`T`), which will be updated whenever the state changes. * 2. A function to update the state (`setStateAction`), which can accept either a direct value or a function that takes the current state and returns the new state. * * @template T - The type of the state value. It can be any type (e.g., `string`, `number`, `boolean`, `object`, etc.). * * @example * // Using with a direct initial state value * const [count, setCount] = useMState(0); * * // Using with an initializer function * const [user, setUser] = useMState(() => ({ name: 'John', age: 30 })); * * // Updating state based on previous state * setUser(mostRecentSnapshot => mostRecentSnapshot.age += 1); */ export declare function useMState<T = unknown>(initialState: T | InitializerAction<T>): UseMState<T>;