Efficient way to organise UI components
Functional Components and Hooks
Alex Li
1.
Older versions (before October, 2015)
Class component only
2.
0.14.0 (October, 2015)
Functional component was added into React
3.
16.8.0 (February, 2019)
Hooks were added into React
4.
17.0.0 (October, 2020)
Concurrent mode (time slicing, suspense)
Functional Components are simple plain javascript functions which return JSX.
What is functional component
const Header = (props) => (
<div>
<h1>{props.title}</h1>
<h2>{props.subtitle}</h2>
</div>
);
<Header title="Title"
subtitle="Sub title"
/>
Why functional component?

Difference
Class Component
Stateful
Lifecycle methods
Rely on this
Error boundary
Functional Component
Stateful
Lifecycle methods
Rely on this
Error boundary
- Simple, less code and smaller bundle
- Stateless and idempotent
Motivations (before having hooks)
Much smaller bundle size
A functional approach to UI

Segregate State Container and Presentation

With Redux

React hooks make fill in the gaps between functional component and class component and even beyond it.
React Hooks!

- Managing state
- Managing side effects
- Caching
- Managing refs
What are hooks?
Hooks are a set of functions which can only be used by functional components for
Most frequency hooks

useState example
useEffect example
Reuse code



Reusable code pattern should always be concerned

An example
In functional programming, there is a well-known concept named high-order functional. HOC is a similar thing in react. A HOC is usually a:
Reuse logic with HOC
- A function
- Argument is a component
- Returns a new component
HOC Example
- Hard contract is required between HOC and view component
- Nested hell
Disadvantages
withErrorState(withAuth(withAdContext(withDeviceSize(withResizeable(withDraggable(...))))))
Render props is a similar pattern with HOC but with some differences:
Reuse logic with render props
- It is a component not a function
- View component is composite via children or other props
Render props Example
Custom Hook Example
UI=F(props, H1(param), H2(param),...Hn(param))
The mental model is changed
Do you think virtual DOM fast?
Memorization
Mutate DOM process

Just like GC technology, Virtual dom technology is aiming to find out a balanced solution between development experience and render performance. The key to success in react application performance is reduce unnecessary re-rendering

useMemo example
Replace redux with hooks

Q&A
Additional Reading
- React Today and Tomorrow and 90% Cleaner React With Hooks
- Time slicing and suspense produced by Dan
- Construct layered hooks for your app (sorry, this article is written in Chinese, I can't find an English version but I strongly recommend it. You can use some translate tools for reading it)
Functional Components and Hooks
By Alex Li
Functional Components and Hooks
- 197