Created
January 5, 2024 07:04
-
-
Save eczn/9a193b30ed302107180e98d5f573e3db to your computer and use it in GitHub Desktop.
createSignal for react
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
import React from 'react'; | |
/** createSignal for react */ | |
export function createSignal<S>( | |
initialState: S | |
): [() => S, (nextState: S) => void] { | |
const forceRender = useForceRender(); | |
const stateRef = React.useRef<S>(initialState); | |
const stateRefGetter = (): S => stateRef.current; | |
const stateSetter = React.useCallback((nextState: S) => { | |
stateRef.current = nextState; | |
forceRender(); // need to rerender the react component | |
}, []); | |
return [stateRefGetter, stateSetter]; | |
} | |
function useForceRender() { | |
const [_, set] = React.useState({}); | |
// every runs gives a different object to renrender component (pointer) | |
return () => set({}); | |
} | |
// demo | |
export default function App() { | |
const [count, setCount] = createSignal(0); | |
React.useEffect(() => { | |
const timer = setInterval(() => { | |
setCount(count() + 1); | |
}, 500); | |
console.log(`created`, count()); // always get the latest value of counter state, but not the prev closured one | |
return () => { | |
console.log("clear interval ?", count()); // would never run clear interval when setCount | |
clearInterval(timer); | |
}; | |
}, []); | |
return <div>count: {count()}</div>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this line of code executes once was mounted, while the first time of setInterval callback will runs after 500ms.