RxJS Hooks and Suspense: The Ultimate Guide

Why Hooks

“This” isn’t the way

Time travelling

Get on the Hook

Why RxJS in Hooks

Observable Hooks

import React from 'react'
import { useObservableState } from 'observable-hooks'
import { timer } from 'rxjs'
import { switchMap, mapTo, startWith } from 'rxjs/operators'
const App = () => {
const [isTyping, updateIsTyping] = useObservableState(
event$ => event$.pipe(
switchMap(() =>
timer(1000).pipe(
mapTo(false),
startWith(true)
)
)
),
false
)
return (
<div>
<input type="text" onKeyDown={updateIsTyping} />
<p>{isTyping ? 'Good you are typing.' : 'Why stop typing?'}</p>
</div>
)
}
Pomodoro Timer Example

Suspense

Render-as-You-Fetch (using Suspense)
// api.js
import { ObservableResource } from 'observable-hooks'
const postResource$$ = new Subject()export const postsResource = new ObservableResource(postResource$$.pipe(
switchMap(id => fakePostsXHR(id))
))
export function fetchPosts(id) {
postResource$$.next(id)
}
// App.jsx
import { useObservableSuspense } from 'observable-hooks'
import { postsResource, fetchPosts } from './api'fetchPosts('crimx')function ProfilePage() {
return (
<Suspense fallback={<h1>Loading posts...</h1>}>
<ProfileTimeline />
</Suspense>
)
}
function ProfileTimeline() {
// Try to read posts, although they might not have loaded yet
const posts = useObservableSuspense(postsResource)
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.text}</li>
))}
</ul>
)
}

Conclusion

https://github.com/crimx

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Avoid multiple try catch async await in JavaScript

Explain Angularjs or I18n Angular internalization

How to Make a Reusable React Native Button Component

3 Tips for Chrome DevTools Users

Tutorial: Animate the Opening Star Wars Crawl in a React App with GreenSock

Collecting browser console logs in Stackdriver

Schematic diagram for browser log shipping to Stackdriver

Spring @Transactional and Exceptions

Fallback for Blocked Iframes: A (Crude) Solution with Vue.js

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
CRIMX

CRIMX

https://github.com/crimx

More from Medium

A TypeScript Type-Guard for Filtering out undefined Values

How to build an inclusive work environment

Aagje Reynders, inclusion blog

Creating a custom icon generator for MUI

A snippet of code from the MUI icon generated by this project.

Typescript — Partial ,Parameter and Keyof Keyword