Last active
May 9, 2023 16:02
-
-
Save 12cassie34/e52e5b9931e4128a610765a9000fa3fd to your computer and use it in GitHub Desktop.
Create my Own React Signal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let currentListener = undefined | |
const createEffect = (callback) => { | |
currentListener = callback | |
callback() | |
currentListener = undefined | |
} | |
// Use case | |
createEffect(() => { | |
console.log(someSignal()) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const createSignal = (initialValue) => { | |
let value = initialValue | |
// a set of callback functions, from createEffect | |
const subscribers = new Set() | |
const read = () => { | |
if (currentListener !== undefined) { | |
// before returning, track the current listener | |
subscribers.add(currentListener) | |
} | |
return value | |
} | |
const write = (newValue) => { | |
value = newValue | |
// after setting the value, run any subscribers | |
subscribers.forEach(subscriber => subscriber()) | |
} | |
return [read, write] | |
} | |
// Usecase | |
const [count, setCount] = createSignal(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment