Last active
August 2, 2022 14:34
-
-
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.
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 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