|
| 1 | +/** |
| 2 | + * @title recho.state(value) |
| 3 | + */ |
| 4 | + |
| 5 | +/** |
| 6 | + * ============================================================================ |
| 7 | + * = recho.state(value) = |
| 8 | + * ============================================================================ |
| 9 | + * |
| 10 | + * Creates a reactive state variable that can be mutated over time. This is |
| 11 | + * similar to React's useState hook and enables mutable reactive values that |
| 12 | + * automatically trigger re-evaluation of dependent blocks when changed. |
| 13 | + * |
| 14 | + * @param {any} value - The initial state value. |
| 15 | + * @returns {[any, Function, Function]} A tuple containing: |
| 16 | + * - state: The reactive state value that can be read directly |
| 17 | + * - setState: Function to update the state (accepts value or updater function) |
| 18 | + * - getState: Function to get the current state value |
| 19 | + */ |
| 20 | + |
| 21 | +// Basic counter that increments after 1 second |
| 22 | +const [count1, setCount1] = recho.state(0); |
| 23 | + |
| 24 | +setTimeout(() => { |
| 25 | + setCount1(count1 => count1 + 1); |
| 26 | +}, 1000); |
| 27 | + |
| 28 | +//➜ 1 |
| 29 | +echo(count1); |
| 30 | + |
| 31 | +// Timer that counts down from 10 |
| 32 | +const [timer, setTimer] = recho.state(10); |
| 33 | + |
| 34 | +{ |
| 35 | + const interval = setInterval(() => { |
| 36 | + setTimer(t => { |
| 37 | + if (t <= 0) { |
| 38 | + clearInterval(interval); |
| 39 | + return 0; |
| 40 | + } |
| 41 | + return t - 1; |
| 42 | + }); |
| 43 | + }, 1000); |
| 44 | + |
| 45 | + invalidation.then(() => clearInterval(interval)); |
| 46 | +} |
| 47 | + |
| 48 | +//➜ 8 |
| 49 | +echo(`Time remaining: ${timer}s`); |
| 50 | + |
| 51 | +// State can be updated with a direct value |
| 52 | +const [message, setMessage] = recho.state("Hello"); |
| 53 | + |
| 54 | +setTimeout(() => { |
| 55 | + setMessage("Hello, World!"); |
| 56 | +}, 2000); |
| 57 | + |
| 58 | +//➜ "Hello, World!" |
| 59 | +echo(message); |
| 60 | + |
| 61 | +// Multiple states can be used together |
| 62 | +const [firstName, setFirstName] = recho.state("John"); |
| 63 | +const [lastName, setLastName] = recho.state("Doe"); |
| 64 | + |
| 65 | +setTimeout(() => { |
| 66 | + setFirstName("Jane"); |
| 67 | + setLastName("Smith"); |
| 68 | +}, 1500); |
| 69 | + |
| 70 | +//➜ "Jane Smith" |
| 71 | +echo(`${firstName} ${lastName}`); |
| 72 | + |
0 commit comments