optimize react hooks

main
Mike Fix 6 years ago
parent d3d5e56a9e
commit 270cb0f5cd

@ -6,12 +6,12 @@ import ApiContext from './ApiContext'
import PhotoCredit from './PhotoCredit'
function RandomImage(props) {
const { current: cache } = React.useRef([])
const cacheRef = React.useRef([])
const [cacheIndex, updateIndex] = React.useState(0)
const api = React.useContext(ApiContext)
const [selectImage, { loading: selecting }] = useAsyncCallback(() => {
const image = cache[cacheIndex]
const image = cacheRef.current[cacheIndex]
return api.unsplash.download(image.id).then(blob => props.onChange(blob, image))
})
@ -20,20 +20,23 @@ function RandomImage(props) {
api.unsplash.random
)
const needsFetch = !error && !updating && (!imgs || cacheIndex > cache.length - 2)
React.useEffect(() => {
if (!error && !updating && (!imgs || cacheIndex > cache.length - 2)) {
if (needsFetch) {
updateCache()
}
}, [error, updating, imgs, cacheIndex, cache.length, updateCache])
}, [needsFetch, updateCache])
React.useEffect(() => {
if (imgs) {
cache.push(...imgs)
cacheRef.current.push(...imgs)
}
}, [cache, imgs])
}, [imgs])
const loading = updating || selecting
const cache = cacheRef.current
const photographer = cache[cacheIndex] && cache[cacheIndex].photographer
const bgImage = cache[cacheIndex] && cache[cacheIndex].dataURL
return (

@ -5,12 +5,13 @@ import ApiContext from './ApiContext'
import Button from './Button'
function useWindowListener(key, fn) {
const { current: callback } = React.useRef(fn)
const callbackRef = React.useRef(fn)
React.useEffect(() => {
window.addEventListener(key, callback)
return () => window.removeEventListener(key, callback)
}, [key, callback])
const cb = callbackRef.current
window.addEventListener(key, cb)
return () => window.removeEventListener(key, cb)
}, [key])
}
function useOnlineListener() {
@ -22,7 +23,7 @@ function useOnlineListener() {
? navigator.onLine
: true
)
}, [setOnline])
}, [])
useWindowListener('offline', () => setOnline(false))
useWindowListener('online', () => setOnline(true))

@ -19,7 +19,7 @@
"now-build": "cross-env NODE_ENV=production yarn build && yarn export -o dist"
},
"dependencies": {
"@dawnlabs/tacklebox": "^0.0.4",
"@dawnlabs/tacklebox": "^0.0.5",
"axios": "^0.18.0",
"codemirror": "^5.42.2",
"codemirror-graphql": "^0.8.3",

@ -775,10 +775,10 @@
debug "^3.1.0"
lodash.once "^4.1.1"
"@dawnlabs/tacklebox@^0.0.4":
version "0.0.4"
resolved "https://registry.yarnpkg.com/@dawnlabs/tacklebox/-/tacklebox-0.0.4.tgz#ee84ab6eaf141e9fbd5d8cc03964fc5db9c01bd0"
integrity sha512-Wa5IBblxFHZ9OmUgw6bitnas4J9Ta0UMeBGePXuymxgIxXQKbpd7RmY8Syw8Fyhn6lXlXteL98fL21V64DgwQQ==
"@dawnlabs/tacklebox@^0.0.5":
version "0.0.5"
resolved "https://registry.yarnpkg.com/@dawnlabs/tacklebox/-/tacklebox-0.0.5.tgz#e33b1983c576bb617c01d516b1f7419a6c5d299a"
integrity sha512-DFyQ7FbEVwzOkg/sNSey7J98s/XXBbT0U9AGrCVuQpbC8VrrLCzgKlbeexJfVFvTm5B1tFTmzne3vpAmBezY0A==
dependencies:
copy-to-clipboard "^3.0.8"
react-click-outside "^3.0.1"

Loading…
Cancel
Save