Captain Hook, and His Complicits - abukhalil-LTUC-ASAC/amman-401d4 GitHub Wiki
What is the problem, lads?
While building the past app, RESTy, you might have noticed that moving state changes across different levels is extremely counterintuitive, and requires callbacks after callbacks to each single layer you want to move over from and to, a solution was to make a huge non reusable component but that defeats the purpose of react right? But then duplicated logic appears and does not feel good or dry at all. However, captain Hook seems to hold the answer.
Round them and hook them up!
What might initially be a bloated solution, you could easily be duped by the initial extra work, but trust this article it wont, and would end up even smaller than you thought it might end up to be.
The abstraction uses an encapsulating function, and a "state" constant [state, setState] = useState(initialValue)
. With this your function could operate like a class with states while still keeping the code as minimal as possible. state
represents the value we want to observe and setState
is the function call whenever we want the state
value changed. These are wrapped around something that is called useEffect(() => {})
, and any changed defined by the logic inside is observed and reacted apon.
Laws of the hook.
- Be at the top: only top level should the hook reside, don't even try to implement it inside a function loop and anything else in a component, or else you wont like the lack of response.
- Call hook where it is available: that would be from react functions, and from custom hooks.
You might be intimidated by the complexity
But it is easy, check out how to deal with data passing around different functions with this sweet documentation.