Skip to content

Commit

Permalink
Prevent extraneous re-renders with next/dynamic (#11587)
Browse files Browse the repository at this point in the history
* Prevent extraneous rerenders with loadables

* Don't try to spread undefined

* Allow ref to be memoized
  • Loading branch information
devknoll authored Apr 2, 2020
1 parent 5db180b commit 139da5a
Showing 1 changed file with 28 additions and 24 deletions.
52 changes: 28 additions & 24 deletions packages/next/next-server/lib/loadable.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,29 +164,35 @@ function createLoadableComponent(loadFn, options) {
const context = React.useContext(LoadableContext)
const state = useSubscription(subscription)

React.useImperativeHandle(ref, () => ({
retry: subscription.retry,
}))
React.useImperativeHandle(
ref,
() => ({
retry: subscription.retry,
}),
[]
)

if (context && Array.isArray(opts.modules)) {
opts.modules.forEach(moduleName => {
context(moduleName)
})
}

if (state.loading || state.error) {
return React.createElement(opts.loading, {
isLoading: state.loading,
pastDelay: state.pastDelay,
timedOut: state.timedOut,
error: state.error,
retry: subscription.retry,
})
} else if (state.loaded) {
return opts.render(state.loaded, props)
} else {
return null
}
return React.useMemo(() => {
if (state.loading || state.error) {
return React.createElement(opts.loading, {
isLoading: state.loading,
pastDelay: state.pastDelay,
timedOut: state.timedOut,
error: state.error,
retry: subscription.retry,
})
} else if (state.loaded) {
return opts.render(state.loaded, props)
} else {
return null
}
}, [props, state])
}

LoadableComponent.preload = () => init()
Expand Down Expand Up @@ -243,12 +249,12 @@ class LoadableSubscription {

this._res.promise
.then(() => {
this._update()
this._update({})
this._clearTimeouts()
})
// eslint-disable-next-line handle-callback-err
.catch(err => {
this._update()
this._update({})
this._clearTimeouts()
})
this._update({})
Expand All @@ -257,6 +263,9 @@ class LoadableSubscription {
_update(partial) {
this._state = {
...this._state,
error: this._res.error,
loaded: this._res.loaded,
loading: this._res.loading,
...partial,
}
this._callbacks.forEach(callback => callback())
Expand All @@ -268,12 +277,7 @@ class LoadableSubscription {
}

getCurrentValue() {
return {
...this._state,
error: this._res.error,
loaded: this._res.loaded,
loading: this._res.loading,
}
return this._state
}

subscribe(callback) {
Expand Down

0 comments on commit 139da5a

Please sign in to comment.