Skip to content

useCloned

Category
Export Size
1.01 kB
Last Changed
5 days ago

Reactive clone of a value. By default, it use JSON.parse(JSON.stringify()) to do the clone

Demo

Usage

tsx
import { 
useCloned
} from '@reause/core'
const [
original
,
setOriginal
] =
useState
({
key
: 'value' })
const [
cloned
,
setCloned
, {
isModified
,
sync
}] =
useCloned
({
value
:
original
,
onChange
:
setOriginal
,
}) // on the next render `cloned` is the new state and `isModified` is true
setCloned
({
key
: 'some new value' })
console
.
log
(
cloned
.
key
) // 'some new value' (next render)
sync
() // re-clone from the source, isModified back to false

Manual cloning

tsx
import { 
useCloned
} from '@reause/core'
const [
original
,
setOriginal
] =
useState
({
key
: 'value' })
const [
cloned
, , {
sync
}] =
useCloned
(
{
value
:
original
,
onChange
:
setOriginal
},
{
manual
: true }
)
setOriginal
({
key
: 'manual' })
console
.
log
(
cloned
.
key
) // 'value'
sync
()
console
.
log
(
cloned
.
key
) // 'manual'

Custom Clone Function

Using klona for example:

tsx
import { 
useCloned
} from '@reause/core'
import {
klona
} from 'klona'
const [
original
,
setOriginal
] =
useState
({
key
: 'value' })
const [
cloned
, , {
isModified
,
sync
}] =
useCloned
(
{
value
:
original
,
onChange
:
setOriginal
},
{
clone
:
klona
}
)

Type Declarations

ts
export interface UseClonedOptions<T = any> {
    clone?: (source: T) => T;
    manual?: boolean;
    deep?: boolean;
    immediate?: boolean;
}

export type UseClonedReturn<T> = readonly [
    cloned: T,
    setCloned: Dispatch<SetStateAction<T>>,
    controls: {
        isModified: boolean;
        sync: () => void;
    }
]

export type CloneFn<F, T = F> = (x: F) => T

export function cloneFnJSON<T>(source: T): T

export function useCloned<T>(source: State<T>, options?: UseClonedOptions<T>): UseClonedReturn<T>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
95f80 - fix(core): return [cloned, setCloned, { isModified, sync }] from useCloned
91b71 - fix(core): accept State source in useCloned (#524)
0cb5d - fix(core): resolve useCloned audit findings (#524)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8