Last active
April 25, 2024 21:20
-
-
Save innateessence/2317b2de692a9ead8eeefcc883235a3a to your computer and use it in GitHub Desktop.
Reacts' useEffect hook, written in python [naive implementation]
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
#!/usr/bin/env python3 | |
class Observable: | |
def __init__(self, value): | |
self._value = value | |
self._subscribers = [] | |
@property | |
def value(self): | |
return self._value | |
@value.setter | |
def value(self, value): | |
self._value = value | |
for subscriber in self._subscribers: | |
subscriber() | |
class Observer: | |
def __init__(self, observable, callback): | |
self._observable = observable | |
self._callback = callback | |
self._observable._subscribers.append(self) | |
def __call__(self): | |
self._callback() | |
class UseEffect: | |
def __init__(self, callback, depdenency_array): | |
self._observers = [] | |
self._callback = callback | |
for dep in depdenency_array: | |
observer = Observer(dep, self._callback) | |
self._observers.append(observer) | |
def foo(): | |
global x | |
print("x changed to", x.value) | |
x = Observable(10) | |
hook = UseEffect(foo, [x]) | |
x.value = 20 | |
x.value = 30 | |
x.value = 40 | |
x.value = 50 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment