Skip to content

Instantly share code, notes, and snippets.

@klauskpm
Last active August 2, 2022 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klauskpm/71890c934058245d4fe60ce72486c96a to your computer and use it in GitHub Desktop.
Save klauskpm/71890c934058245d4fe60ce72486c96a to your computer and use it in GitHub Desktop.
An example of how to create a hook, share a context and loop on state changes.
let contextCounter = 0;
let sharedContext = [];
let innitializedContext = [];
let wasContextUpdated = false;
function createContext(lifecycle) {
sharedContext = [];
innitializedContext = []
const loop = () => {
contextCounter = 0;
wasContextUpdated = false;
lifecycle();
if (shouldLoop()) loop();
};
return loop;
}
function shouldLoop() {
return wasContextUpdated;
}
function getContextValue(index) {
return sharedContext[index];
}
function setContextAsUpdated(index) {
wasContextUpdated = true;
}
function setContextValue(index, value) {
const currentValue = sharedContext[index];
if (value !== currentValue) {
sharedContext[index] = value;
return true;
}
return false;
}
function useState(value) {
const index = contextCounter;
const currentValue = getContextValue(index);
if (!innitializedContext[index]) {
setContextValue(index, value);
innitializedContext[index] = true;
};
const updateState = (newValue) => {
const hasChanged = setContextValue(index, newValue);
if (hasChanged) setContextAsUpdated(index);
};
contextCounter++;
const newValue = getContextValue(index);
return [newValue, updateState];
}
const comp = createContext(() => {
const [state, setState] = useState(1);
const [otherState, setOtherState] = useState(25);
if (state === 1) {
setState(5)
}
if (otherState === 25 && state === 5) {
setOtherState(12);
}
console.log('state', state);
console.log('otherState', otherState);
});
comp();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment