Skip to content

Instantly share code, notes, and snippets.

@eczn
Created January 5, 2024 07:04
Show Gist options
  • Save eczn/9a193b30ed302107180e98d5f573e3db to your computer and use it in GitHub Desktop.
Save eczn/9a193b30ed302107180e98d5f573e3db to your computer and use it in GitHub Desktop.
createSignal for react
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>;
}
@Crazy492
Copy link

Crazy492 commented Jan 8, 2024

console.log(created, count()); // always get the latest value of counter state, but not the prev closured one

Should this line be written to the timer?

@eczn
Copy link
Author

eczn commented Jan 14, 2024

console.log(created, count()); // always get the latest value of counter state, but not the prev closured one

Should this line be written to the timer?

this line of code executes once was mounted, while the first time of setInterval callback will runs after 500ms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment