-
-
Save ergenekonyigit/bc61b58e67c22286e5cbceaf4c895eaf to your computer and use it in GitHub Desktop.
This file contains hidden or 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 hooks = []; | |
let idx = 0; | |
export function useState(initialState) { | |
let state = hooks[idx] || initialState; | |
let _idx = idx; | |
function setState(newState) { | |
hooks[_idx] = newState; | |
render(); | |
} | |
idx++; | |
return [state, setState]; | |
} | |
export function useEffect(callbackFn, deps) { | |
const prevDeps = hooks[idx]; | |
let hasChanged = true; | |
if(prevDeps) { | |
hasChanged = deps.some((dep, i) => !Object.is(dep, prevDeps[i])) | |
} | |
if(hasChanged) callbackFn(); | |
hooks[idx] = deps; | |
idx++; | |
} | |
export function useRef() { | |
} | |
export function createElement(type, props, ...children) { | |
return {type, props, children} | |
} | |
export function renderElement(element) { | |
const {type, props, children} = element; | |
if(typeof type === 'function') { | |
return renderElement(type(props)); | |
} | |
const domElement = document.createElement(type); | |
children.forEach(child => { | |
let node; | |
if(typeof child === 'string') { | |
node = document.createTextNode(child); | |
} else { | |
node = renderElement(child) | |
} | |
domElement.appendChild(node); | |
}) | |
Object.keys(props).forEach(key => { | |
if(key.startsWith('on')) { | |
const eventName = key.slice(2).toLowerCase(); | |
domElement.addEventListener(eventName, props[key]) | |
} | |
}) | |
return domElement; | |
} | |
let _currentApp = null; | |
let _element = null; | |
let _container = null; | |
export function render(element = _element, container = _container) { | |
const app = renderElement(element); | |
_element = element; | |
_container = container; | |
_currentApp ? | |
container.replaceChild(app, _currentApp) | |
: container.appendChild(app) | |
_currentApp = app; | |
idx = 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment