Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 3x 3x 3x 4x 4x | import { useRef } from 'react'
import { State } from 'watch-state'
/**
* Creates a `State` instance that can be passed as a static prop to child components.
* Reactivity is activated only in components that call `useWatch` on the Observable.
* This pattern optimizes re-renders: parent components don't re-render when state changes.
*
* @template S - The type of the state value
* @param defaultValue - Optional initial value for the state
* @returns A `State` instance
*
* @example
* ```tsx
* // Basic usage //
*
* import { useWatch, useNewState } from '@watch-state/react'
*
* const Parent = () => {
* const $count = useNewState(0)
*
* return <Child $count={$count} />
* }
*
* const Child = ({ $count }) => {
* const count = useWatch($count)
*
* return (
* <div>
* <span>{count}</span>
* <button onClick={() => $count.value++}>+</button>
* </div>
* )
* }
* ```
*/
export function useNewState<T = never> (...args: T extends never | undefined ? [T?] : [T]): State<T>
export function useNewState<T = never> (defaultValue?: any): State<T> {
const ref = useRef<State<T>>()
return ref.current || (ref.current = new State<typeof defaultValue>(defaultValue))
}
|