Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create useMutableValue and useMutableValues #311

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions packages/core/src/Hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,52 @@ export const useDebug = (values: { [key: string]: Animated.Node<number> }) => {
values,
]);
};

/**
* Any change in the value that occurred will be applied to the same Animated.Value returned
* @param value
* @returns Is mutable Animated.Value
*/
export const useMutableValue = <V extends Atomic>(
value: V
): Animated.Value<V> => {
const valueRef = useRef(value);
const animValue = useConst(() => new Value(value));

useCode(() => {
if (valueRef.current === value) {
return false;
}
valueRef.current = value;

return set(animValue, value) as Animated.Node<number>;
}, [value]);

return animValue;
};

/**
* Any change in the values that occurred will be applied to the same Animated.Value returned
* @param values
* @returns Is array of mutable Animated.Value
*/
export const useMutableValues = (<V extends Atomic>(
...values: [V, ...V[]]
): unknown => {
const valueRef = useRef(values);
const animValues = useConst(() => values.map((v) => new Value(v)));

useCode(() => {
if (
valueRef.current.length === values.length &&
valueRef.current.findIndex((v, i) => v !== values[i]) === -1
) {
return false;
}
valueRef.current = values;

return block(values.map((v: Atomic, i: number) => set(animValues[i], v)));
}, values);

return animValues;
}) as UseValues;