Skip to content

Commit

Permalink
Adding deps list to useModel
Browse files Browse the repository at this point in the history
  • Loading branch information
soxtoby committed Mar 24, 2024
1 parent 5376b5a commit a986486
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
11 changes: 7 additions & 4 deletions packages/event-reduce-react/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import { dispose } from "event-reduce/lib/utils";
import { DependencyList, useMemo, useRef } from "react";
import { useDispose, useOnce } from "./utils";

/** Creates a model that persists across renders of the component and cleans up when the component is unmounted. */
export function useModel<T extends object>(createModel: () => T) {
/**
* Creates a model that persists across renders of the component and cleans up when the component is unmounted.
* @param unobservableDependencies - A list of dependencies that are not observable. The model will be re-created when any of these change.
*/
export function useModel<T extends object>(createModel: () => T, unobservableDependencies?: DependencyList) {
let modelOwner = useOnce(() => ({})); // Effectively makes the component the owner of the model for cleanup purposes
let model = useOnce(() => {
let model = useMemo(() => {
let model = createModel();
changeOwnedValue(modelOwner, undefined, model);
return model;
});
}, unobservableDependencies ?? []);
useDispose(() => disposeModel(modelOwner));
return model;
}
Expand Down
8 changes: 3 additions & 5 deletions packages/event-reduce-react/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { useEffect, useRef } from "react";
import { useEffect, useState } from "react";

export function useDispose(dispose: () => void) {
useEffect(() => () => dispose(), []);
}

export function useOnce<T>(getValue: () => T) {
let ref = useRef<T>(undefined!);
if (ref.current === undefined)
ref.current = getValue();
return ref.current;
let [value] = useState(getValue);
return value;
}

0 comments on commit a986486

Please sign in to comment.