Skip to content

Instantly share code, notes, and snippets.

@nirkaufman
Created September 3, 2020 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nirkaufman/1601e51f554b5a47728ab8b091f35254 to your computer and use it in GitHub Desktop.
Save nirkaufman/1601e51f554b5a47728ab8b091f35254 to your computer and use it in GitHub Desktop.
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