Decoupling from the State Layer
Custom Hooks to the Rescue!
Hi! ๐
My name is Iago.
What are hooks?
A feature provided by libraries for isolating, reusing and composing stateful logic.
A concept independently of library...
...that allows us to handle stateful logic, detached from the view.
Libraries
What about custom hooks?
A new hook, being composed by thirdy party hooks or other custom hooks.
Why should I care? ๐ค
Coupling...
...is the degree of interdependence between software modules.
Tight โ
- Dependent of each other
- No clearer data flow
- Harder to read, refactor and test
Loose โ
- Can be used separately
- Clearer separation of responsibilities
- Much easier to understand
Coupling in UI libraries...
View
- Handles presentation
- Semantics (HTML)
- Styling (CSS)
State
- Handles behavior
- Stateful logic
- Async calls
Decoupled View and State
- Better composability and reusability
- Clearer separation of concerns
- Good testability
Custom Hooks to the Rescue
1. The Rules
A. Custom hooks should obey every other rules dictated by the library you are using.
B. Custom hooks should not leak or reveal the technology being used underneath.
C. Custom hooks should not expose the shape of the state being stored.
D. A custom hook should not cover too much state.
2. The line between view and state
useArticles
3. Custom Hook's Public Interface
State Shape
useArticles
useArticles
Actions โ
Actions โ
4. Implementing it Internally
Redux
useSelector and useDispatch
useSelector
useDispatch
Redux
Redux
Redux
Context API: Provider
Context API
View
State
How to Test Components using Custom Hooks
Mocking Paths
Mocking Provider
Wrapping it up
- What are custom hooks
- Why we should care about decoupling the state from the view
- How to implement with different strategies
- How to test it
References
Thanks!
iagodahlem.com
@iagodahlem