Member-only story
In depth exploration of the working principle of React Hooks
Hook is a simpler way to encapsulate stateful behavior and side effects in user interfaces. they Initially introduced in React [5]And was compared to othersVue[6]、Svelte[7]The framework has been widely adopted and even transformed into General functional JS [8]Plan. However, their functional design requires a good understanding of JavaScript closures.
In this article, we reintroduce closures by building a simplified version of React Hook. There are two purposes: to demonstrate how to effectively use closures and to show how to build a mini JS Hooks using only 29 lines of code. Finally, let’s talk about how custom hooks are naturally generated.
⚠️ Note: To understand Hooks, you do not need to follow these steps. If you want to improve your JS basics through this exercise, it may be helpful. Don’t worry, it’s not difficult!
What is a closure?
Hook’s One of the selling points [9]It can completely avoid the complexity of classes and higher-order components. However, some people believe that using hooks is simply replacing one problem we need to solve with another. Now, we don’t have to worry Binding context [10]But instead You have to worry about closures [11]Just like Mark Dalgleish This is what was said [12]: