Skip to content

Commit

Permalink
Avoid unnecessary selector evaluations
Browse files Browse the repository at this point in the history
  • Loading branch information
josepot committed May 2, 2019
1 parent d849ede commit c332fa3
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 26 deletions.
61 changes: 36 additions & 25 deletions src/hooks/useSelector.js
@@ -1,4 +1,4 @@
import { useReducer, useRef, useEffect, useMemo, useLayoutEffect } from 'react'
import { useState, useRef, useEffect, useMemo, useLayoutEffect } from 'react'
import invariant from 'invariant'
import { useReduxContext } from './useReduxContext'
import shallowEqual from '../utils/shallowEqual'
Expand Down Expand Up @@ -42,7 +42,7 @@ export function useSelector(selector) {
invariant(selector, `You must pass a selector to useSelectors`)

const { store, subscription: contextSub } = useReduxContext()
const [, forceRender] = useReducer(s => s + 1, 0)
const [state, setState] = useState({ id: 0, state: null })

const subscription = useMemo(() => new Subscription(store, contextSub), [
store,
Expand All @@ -51,31 +51,13 @@ export function useSelector(selector) {

const latestSubscriptionCallbackError = useRef()
const latestSelector = useRef(selector)

let selectedState = undefined

try {
selectedState = selector(store.getState())
} catch (err) {
let errorMessage = `An error occured while selecting the store state: ${
err.message
}.`

if (latestSubscriptionCallbackError.current) {
errorMessage += `\nThe error may be correlated with this previous error:\n${
latestSubscriptionCallbackError.current.stack
}\n\nOriginal stack trace:`
}

throw new Error(errorMessage)
}

const latestSelectedState = useRef(selectedState)
const latestSelectedState = useRef()
const latestId = useRef(0)

useIsomorphicLayoutEffect(() => {
latestSelector.current = selector
latestSelectedState.current = selectedState
latestSubscriptionCallbackError.current = undefined
latestId.current = state.id
})

useIsomorphicLayoutEffect(() => {
Expand All @@ -96,7 +78,10 @@ export function useSelector(selector) {
latestSubscriptionCallbackError.current = err
}

forceRender({})
setState(prev => ({
id: prev.id + 1,
state: latestSelectedState.current
}))
}

subscription.onStateChange = checkForUpdates
Expand All @@ -107,5 +92,31 @@ export function useSelector(selector) {
return () => subscription.tryUnsubscribe()
}, [store, subscription])

return selectedState
try {
latestSelectedState.current = useMemo(() => selector(store.getState()), [
selector
])

if (state.id != latestId.current) {
if (latestSubscriptionCallbackError.current) {
latestSelectedState.current = selector(store.getState())
return latestSelectedState.current
}
return state.state
}
} catch (err) {
let errorMessage = `An error occured while selecting the store state: ${
err.message
}.`

if (latestSubscriptionCallbackError.current) {
errorMessage += `\nThe error may be correlated with this previous error:\n${
latestSubscriptionCallbackError.current.stack
}\n\nOriginal stack trace:`
}

throw new Error(errorMessage)
}

return latestSelectedState.current
}
27 changes: 26 additions & 1 deletion test/hooks/useSelector.spec.js
@@ -1,6 +1,6 @@
/*eslint-disable react/prop-types*/

import React from 'react'
import React, { useCallback } from 'react'
import { createStore } from 'redux'
import { renderHook, act } from 'react-hooks-testing-library'
import * as rtl from 'react-testing-library'
Expand Down Expand Up @@ -31,6 +31,31 @@ describe('React', () => {
expect(result.current).toEqual(0)
})

it('always uses the latest state', () => {
store = createStore(c => c + 1, -1)

const Comp = () => {
const selector = useCallback(c => c + 1, [])
const value = useSelector(selector)
renderedItems.push(value)
return <div />
}

rtl.render(
<ProviderMock store={store}>
<Comp />
</ProviderMock>
)

expect(renderedItems).toEqual([1])

act(() => {
store.dispatch({ type: '' })
})

expect(renderedItems).toEqual([1, 2])
})

it('selects the state and renders the component when the store updates', () => {
const { result } = renderHook(() => useSelector(s => s.count), {
wrapper: props => <ProviderMock {...props} store={store} />
Expand Down

0 comments on commit c332fa3

Please sign in to comment.