Skip to content

Commit

Permalink
Memoize reset values function
Browse files Browse the repository at this point in the history
  • Loading branch information
ArtiomTr committed Dec 3, 2024
1 parent 97fff6d commit 20571e2
Showing 2 changed files with 9 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/four-eels-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'stocked': patch
---

Memoize resetValues function
6 changes: 4 additions & 2 deletions packages/stocked/src/hooks/useStock.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SetStateAction, useCallback, useMemo } from 'react';
import { SetStateAction, useCallback, useMemo, useRef } from 'react';
import cloneDeep from 'lodash/cloneDeep.js';
import isFunction from 'lodash/isFunction.js';
import { createPxth, deepGet, deepSet, Pxth } from 'pxth';
@@ -40,6 +40,8 @@ export type StockConfig<T extends object> = {
*/
export const useStock = <T extends object>({ initialValues, debugName }: StockConfig<T>): Stock<T> => {
const values = useLazyRef<T>(() => cloneDeep(initialValues));
const initialValuesRef = useRef(initialValues);
initialValuesRef.current = initialValues;
const { notifySubTree, notifyAll, watch, watchAll, watchEffect, watchBatchUpdates, isObserved } =
useObservers<T>(values);

@@ -68,7 +70,7 @@ export const useStock = <T extends object>({ initialValues, debugName }: StockCo

const getValues = useCallback(() => values.current, [values]);

const resetValues = useCallback(() => setValues(cloneDeep(initialValues)), [initialValues, setValues]);
const resetValues = useCallback(() => setValues(cloneDeep(initialValuesRef.current)), [setValues]);

const stock: Stock<T> = useMemo(
() => ({

0 comments on commit 20571e2

Please sign in to comment.