Recently, I have read a great post titled ‘Redux vs. The React Context API’ (https://daveceddia.com/context-api-vs-redux). It is the type of the post I liked. It uses a simple example to explain the concept behind scene. The example looks simple, but it let us understand the concept without distractions. After a few minutes, I have learnt Redux and Context API and started to think what if we do the same thing in the AppRun applications. Without further ado, I created the same example on glitch.com.
You can see the live demo on glitch.com. https://apprun-state-2-components.glitch.me/
I will describe the thought process of AppRun to help you understand and compare it with Redux and the Context API.
The HTML
The HTML has site structure.
You can see we mainly use HTML and do not need to have the component structure.
// No need
<App>
<Nav>
<UserAvatar />
</Nav>
<Body>
<Sidebar>
<UserStats />
</Sidebar>
</Body>
</App>
Since we are not forced into the component structure, we leverage the HTML and mount the components to the HTML elements.
The Main Program
In the AppRun application, we mount components to HTML elements.
We only need two components <UserAvatar/> and <UserStats/>. We mount them to the <div> elements that have of ‘user-avatar’ and ‘user-stats’ respectively.
Then we publish an AppRun event ‘/set-user’ with the user data as the event parameter.
The Components
The components subscribe and handle the AppRun event. They get the user data from the event parameter and create a new component state. AppRun then calls the view function with the new state. The view function creates the Virtual DOM using JSX. AppRun then renders the DOM.
The UserAvatar Component
The UserAvatar component displays the avatar image. The state is the avatar URL.
The UserStats Component
The UserStats component displays the user’s avatar image, name and other information. The state is the user object.
AppRun Supports the JSX fragment. We can create a list of elements without a root element to group them. The list of the elements are inserted into the element that the component is mounted to. It helps us to fine tune and get a perfect HTML structure.
That’s all.
Conclusion
Two things have made the AppRun application easier and straightforward. One is that we can mount components to the elements. Two is that we use events to pass the data and trigger the a serials of processes including updating the component states and rendering the DOM.
You can re-mix the example on glitch.com. https://apprun-state-2-components.glitch.me/
For more information about AppRun, please visit https://github.com/yysun/apprun.
Have fun coding and send PRs.