react-inspired-experiments

  1. A simple useState implementation
  2. Sharing data between components

A simple useState implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function useState(initialValue) {
const state = {
_value: initialValue,
get value() {
console.log("getting value:", this._value);
return this._value;
},
set value(newValue) {
console.log("setting value:", newValue);
this._value = newValue;
},
};
const setState = function (newValue) {
state.value = newValue;
};
return [state, setState];
}

Usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function useState(initialValue) {
const state = {
_value: initialValue,
get value() {
console.log("getting value:", this._value);
return this._value;
},
set value(newValue) {
console.log("setting value:", newValue);
this._value = newValue;
},
};
const setState = function (newValue) {
state.value = newValue;
};
return [state, setState];
}

function MyButton() {
const [count, setCount] = useState(0);
const btn = document.createElement("button");

btn.textContent = count.value;
btn.onclick = () => {
setCount(count.value + 1);
btn.textContent = count.value;
};
return btn;
}

document.getElementById("app").appendChild(MyButton());

document.getElementById("app").appendChild(MyButton());

Live demo:

Sharing data between components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function useState(initialValue) {
const state = {
_value: initialValue,
get value() {
console.log("getting value:", this._value);
return this._value;
},
set value(newValue) {
console.log("setting value:", newValue);
this._value = newValue;
},
};
const setState = function (newValue) {
state.value = newValue;
};
return [state, setState];
}

const [count, setCount] = useState(0);
function handleClick() {
setCount(count.value + 1);
render();
}

function MyButton({ count, onClick, id }) {
const btn = document.createElement("button");
btn.id = id;
btn.textContent = `You clicked ${count.value} times.`;
btn.onclick = onClick;
return btn;
}

const btn1RenderFn = function () {
return MyButton({
id: btn1RenderFn.id,
count,
onClick: handleClick,
});
};
btn1RenderFn.id = generateDomID();

const btn2RenderFn = function () {
return MyButton({
id: btn2RenderFn.id,
count,
onClick: handleClick,
});
};
btn2RenderFn.id = generateDomID();

const container = document.getElementById("app");
const children = [btn1RenderFn, btn2RenderFn];

function render() {
children.forEach((child) => {
const oldEl = document.getElementById(child.id);
if (oldEl && container.hasChildNodes(oldEl)) {
oldEl.replaceWith(child());
} else {
container.appendChild(child());
}
});
}

function generateDomID() {
return "dom-" + new Date().valueOf() + "-" + Math.random();
}

render();

Live demo: