신호는 두 가지 주요 목표를 가진 성능있는 주 관리 라이브러리입니다.
발표 게시물을 읽으십시오. 어떤 문제가 해결되는지에 대한 자세한 내용과 그 문제에 대해 자세히 알아보십시오.
# Just the core library
npm install @preact/signals-core
# If you're using Preact
npm install @preact/signals
# If you're using React
npm install @preact/signals-react
# If you're using Svelte
npm install @preact/signals-core
signal(initialValue)
signal.peek()
computed(fn)
effect(fn)
batch(fn)
untracked(fn)
신호 라이브러리는 당신이 생각할 수있는 비즈니스 로직을 모델링하기위한 빌딩 블록 인 4 가지 기능을 노출시킵니다.
signal(initialValue)
signal
기능은 새로운 신호를 만듭니다. 신호는 시간이 지남에 따라 변경 될 수있는 값의 컨테이너입니다. .value
속성에 액세스하여 신호의 값을 읽거나 값 업데이트를 구독 할 수 있습니다.
import { signal } from "@preact/signals-core" ;
const counter = signal ( 0 ) ;
// Read value from signal, logs: 0
console . log ( counter . value ) ;
// Write to a signal
counter . value = 1 ;
신호에 쓰기는 .value
속성을 설정하여 수행됩니다. 신호의 값을 변경하면 해당 신호에 따라 계산 된 모든 계산 및 효과가 동기식으로 업데이트되므로 앱 상태가 항상 일관되도록합니다.
signal.peek()
드문 경우에는 이전 값을 기반으로 다른 신호에 쓸 효과가 있지만 해당 신호에 가입하기를 원하지 않으므로 signal.peek()
을 통해 신호의 이전 값을 읽을 수 있습니다.
const counter = signal ( 0 ) ;
const effectCount = signal ( 0 ) ;
effect ( ( ) => {
console . log ( counter . value ) ;
// Whenever this effect is triggered, increase `effectCount`.
// But we don't want this signal to react to `effectCount`
effectCount . value = effectCount . peek ( ) + 1 ;
} ) ;
실제로 필요한 경우 signal.peek()
만 사용해야합니다. signal.value
통해 신호의 값을 읽는 것은 대부분의 시나리오에서 선호하는 방법입니다.
computed(fn)
데이터는 종종 기존 데이터의 다른 부분에서 파생됩니다. computed
기능을 사용하면 다중 신호 값을 추가 계산에 반응하거나 추가로 사용할 수있는 새로운 신호로 결합 할 수 있습니다. 계산 된 콜백 변경 내에서 액세스 한 신호가 계산 된 콜백이 다시 실행되고 새로운 리턴 값이 계산 된 신호의 값이됩니다.
import { signal , computed } from "@preact/signals-core" ;
const name = signal ( "Jane" ) ;
const surname = signal ( "Doe" ) ;
const fullName = computed ( ( ) => name . value + " " + surname . value ) ;
// Logs: "Jane Doe"
console . log ( fullName . value ) ;
// Updates flow through computed, but only if someone
// subscribes to it. More on that later.
name . value = "John" ;
// Logs: "John Doe"
console . log ( fullName . value ) ;
computed
의 콜백 함수 내부에서 액세스되는 모든 신호는 자동으로 구독하고 계산 된 신호의 종속성으로 추적됩니다.
effect(fn)
effect
함수는 모든 것을 반응하게 만드는 마지막 조각입니다. 콜백 함수 내부의 신호에 액세스하면 해당 신호와 해당 신호의 모든 종속성이 활성화되어 구독됩니다. 이와 관련하여 그것은 computed(fn)
와 매우 유사합니다. 기본적으로 모든 업데이트는 게으르 기 때문에 신호 내부 effect
액세스 할 때까지 업데이트되지 않습니다.
import { signal , computed , effect } from "@preact/signals-core" ;
const name = signal ( "Jane" ) ;
const surname = signal ( "Doe" ) ;
const fullName = computed ( ( ) => name . value + " " + surname . value ) ;
// Logs: "Jane Doe"
effect ( ( ) => console . log ( fullName . value ) ) ;
// Updating one of its dependencies will automatically trigger
// the effect above, and will print "John Doe" to the console.
name . value = "John" ;
반환 된 함수를 호출하여 가입 한 모든 신호에서 효과를 파괴하고 구독을 취소 할 수 있습니다.
import { signal , computed , effect } from "@preact/signals-core" ;
const name = signal ( "Jane" ) ;
const surname = signal ( "Doe" ) ;
const fullName = computed ( ( ) => name . value + " " + surname . value ) ;
// Logs: "Jane Doe"
const dispose = effect ( ( ) => console . log ( fullName . value ) ) ;
// Destroy effect and subscriptions
dispose ( ) ;
// Update does nothing, because no one is subscribed anymore.
// Even the computed `fullName` signal won't change, because it knows
// that no one listens to it.
surname . value = "Doe 2" ;
효과 콜백은 정리 기능을 반환 할 수 있습니다. 효과 콜백이 다음 호출 될 때 또는 효과가 배치 될 때, 먼저 발생하는 경우 정리 기능이 한 번 실행됩니다.
import { signal , effect } from "@preact/signals-core" ;
const count = signal ( 0 ) ;
const dispose = effect ( ( ) => {
const c = count . value ;
return ( ) => console . log ( `cleanup ${ c } ` ) ;
} ) ;
// Logs: cleanup 0
count . value = 1 ;
// Logs: cleanup 1
dispose ( ) ;
batch(fn)
batch
함수를 사용하면 여러 신호 쓰기를 하나의 단일 업데이트로 결합하여 콜백이 완료 될 때 끝에 트리거됩니다.
import { signal , computed , effect , batch } from "@preact/signals-core" ;
const name = signal ( "Jane" ) ;
const surname = signal ( "Doe" ) ;
const fullName = computed ( ( ) => name . value + " " + surname . value ) ;
// Logs: "Jane Doe"
effect ( ( ) => console . log ( fullName . value ) ) ;
// Combines both signal writes into one update. Once the callback
// returns the `effect` will trigger and we'll log "Foo Bar"
batch ( ( ) => {
name . value = "Foo" ;
surname . value = "Bar" ;
} ) ;
콜백 내부에서 이전에 쓴 신호에 액세스하거나 다른 신호로 무효화 된 계산 신호에 액세스하면 읽은 신호의 현재 값을 얻기 위해 필요한 종속성 만 업데이트합니다. 다른 모든 무효화 된 신호는 콜백 함수의 끝에서 업데이트됩니다.
import { signal , computed , effect , batch } from "@preact/signals-core" ;
const counter = signal ( 0 ) ;
const double = computed ( ( ) => counter . value * 2 ) ;
const triple = computed ( ( ) => counter . value * 3 ) ;
effect ( ( ) => console . log ( double . value , triple . value ) ) ;
batch ( ( ) => {
counter . value = 1 ;
// Logs: 2, despite being inside batch, but `triple`
// will only update once the callback is complete
console . log ( double . value ) ;
} ) ;
// Now we reached the end of the batch and call the effect
배치는 중첩 될 수 있으며 가장 바깥 쪽 배치 호출이 완료되면 업데이트가 플러시됩니다.
import { signal , computed , effect , batch } from "@preact/signals-core" ;
const counter = signal ( 0 ) ;
effect ( ( ) => console . log ( counter . value ) ) ;
batch ( ( ) => {
batch ( ( ) => {
// Signal is invalidated, but update is not flushed because
// we're still inside another batch
counter . value = 1 ;
} ) ;
// Still not updated...
} ) ;
// Now the callback completed and we'll trigger the effect.
untracked(fn)
일부 신호를 읽을 수있는 콜백을받을 때 구독을 구독하고 싶지 않은 경우, 구독이 발생하지 않도록 untracked
사용할 수 있습니다.
const counter = signal ( 0 ) ;
const effectCount = signal ( 0 ) ;
const fn = ( ) => effectCount . value + 1 ;
effect ( ( ) => {
console . log ( counter . value ) ;
// Whenever this effect is triggered, run `fn` that gives new value
effectCount . value = untracked ( fn ) ;
} ) ;
MIT
, 라이센스 파일을 참조하십시오.