diff --git a/package.json b/package.json index 5f97710..ffd34f2 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,8 @@ "node": ">=8.9" }, "dependencies": { - "query-string": "^6.9.0" + "query-string": "^6.9.0", + "memoize-one": "^5.1.1" }, "peerDependencies": { "history": "^4", diff --git a/src/lib/store.ts b/src/lib/store.ts index c21a39e..c27ba29 100644 --- a/src/lib/store.ts +++ b/src/lib/store.ts @@ -2,6 +2,7 @@ import { History } from 'history' import LocationState = History.LocationState +import memoizeOne from 'memoize-one' import { stringify } from 'query-string' import { createContext, useContext, useEffect, useMemo, useState } from 'react' import { create, StoreApi, UseStore } from 'zustand' @@ -58,6 +59,27 @@ export const factoryParameters = ( ns: string = DEFAULT_NAMESPACE ) => { const flatConfig = flattenConfig(config) + + const initBlank = (initialQueries: object) => { + // thisValues will be mutated by applyFlatConfigToState, that's why we init it with a copy of + // the initial state. + const thisValues = { ...defaultInitialValues } + const thisQuery = applyFlatConfigToState( + flatConfig, + initialQueries, + ns, + thisValues, + defaultInitialValues + ) + return { + initialValues: defaultInitialValues, + query: thisQuery, + values: thisValues + } + } + + const memInitBlank = memoizeOne(initBlank) + const useQuery = () => { const [useStore, api] = useContext(StoreContext) as [ UseStore>, @@ -100,21 +122,7 @@ export const factoryParameters = ( values } } - // thisValues will be mutated by applyFlatConfigToState, that's why we init it with a copy of - // the initial state. - const thisValues = { ...defaultInitialValues } - const thisQuery = applyFlatConfigToState( - flatConfig, - initialQueries, - ns, - thisValues, - defaultInitialValues - ) - return { - initialValues: defaultInitialValues, - query: thisQuery, - values: thisValues - } + return memInitBlank(initialQueries) }, [api]) const [currentState, setCurrentState] = useState({ diff --git a/yarn.lock b/yarn.lock index aaf3e82..56a5335 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9024,6 +9024,11 @@ mem@^4.0.0: mimic-fn "^2.0.0" p-is-promise "^2.0.0" +memoize-one@^5.1.1: + version "5.1.1" + resolved "https://registry.yarnpkg.com/memoize-one/-/memoize-one-5.1.1.tgz#047b6e3199b508eaec03504de71229b8eb1d75c0" + integrity sha512-HKeeBpWvqiVJD57ZUAsJNm71eHTykffzcLZVYWiVfQeI1rJtuEaS7hQiEpWfVVk18donPwJEcFKIkCmPJNOhHA== + memoizerific@^1.11.3: version "1.11.3" resolved "https://registry.yarnpkg.com/memoizerific/-/memoizerific-1.11.3.tgz#7c87a4646444c32d75438570905f2dbd1b1a805a"