diff --git a/packages/docs-reanimated/docs/advanced/makeMutable.mdx b/packages/docs-reanimated/docs/advanced/makeMutable.mdx new file mode 100644 index 00000000000..14c1d81b536 --- /dev/null +++ b/packages/docs-reanimated/docs/advanced/makeMutable.mdx @@ -0,0 +1,157 @@ +--- +sidebar_position: 9 +--- + +# makeMutable + +:::caution +The usage of `makeMutable` is discouraged in most cases. It's recommended to use the [`useSharedValue`](/docs/core/useSharedValue) hook instead unless you know what you're doing and you are aware of the consequences (see the [Remarks](#remarks) section). + +`makeMutable` is used internally and its behavior may change over time. +::: + +`makeMutable` is a function internally used by the [`useSharedValue`](/docs/core/useSharedValue) hook to create a [shared value](/docs/fundamentals/glossary#shared-value). + +It makes it possible to create mutable values without the use of the hook, which can be useful in some cases (e.g. in the global scope, as an array of mutable values, etc.). + +The created object is, in fact, the same as the one returned by `useSharedValue` hook, so the further usage is the same. + +## Reference + +```javascript +import { makeMutable } from 'react-native-reanimated'; + +const mv = makeMutable(100); +``` + +
+Type definitions + +```typescript +interface SharedValue { + value: Value; + addListener: (listenerID: number, listener: (value: Value) => void) => void; + removeListener: (listenerID: number) => void; + modify: ( + modifier?: (value: T) => T, + forceUpdate?: boolean + ) => void; +} + +function makeMutable(initial: Value): SharedValue; +``` + +
+ +### Arguments + +#### `initial` + +The value you want to be initially stored to a `.value` property. It can be any JavaScript value like `number`, `string` or `boolean` but also data structures such as `array` and `object`. + +### Returns + +`makeMutable` returns a mutable value with a single `value` property initially set to the `initial`. + +Data stored in mutable values can be accessed and modified by their `.value` property. + +## Example + +import MakeMutable from '@site/src/examples/MakeMutable'; +import MakeMutableSrc from '!!raw-loader!@site/src/examples/MakeMutable'; + + + +## Remarks + +:::info +We use _mutable value_ name for an object created by `makeMutable` to distinguish it from the _shared value_ created by `useSharedValue`. Technically, _shared value_ is a _mutable value_ with an automatic cleanup. +::: + +- All remarks from the [useSharedValue](/docs/core/useSharedValue) hook apply to `makeMutable` as well. + +- Don't call `makeMutable` directly in the component scope. When component re-renders, it will create the completely new object (with the new `initial` value if it was changed) and the state of the previous mutable value will be lost. + + + +```javascript +function App() { + const [counter, setCounter] = useState(0); + const mv = makeMutable(counter); // 🚨 creates a new mutable value on each render + + useEffect(() => { + const interval = setInterval(() => { + setCounter((prev) => prev + 1); // updates the counter stored in the component state + }, 1000); + + return () => { + clearInterval(interval); + }; + }, [mv]); + + useAnimatedReaction( + () => mv.value, + (value) => { + console.log(value); // prints 0, 1, 2, ... + } + ); +} +``` + + + +- Use `cancelAnimation` to stop all animations running on the mutable value if it's no longer needed and there are still some animations running. Be super careful with infinite animations, as they will never stop unless you cancel them manually. + + + +```javascript +function App() { + const mv = useMemo(() => makeMutable(0), []); + + useEffect(() => { + mv.value = withRepeat(withSpring(100), -1, true); // creates an infinite animation + + return () => { + cancelAnimation(mv); // ✅ stops the infinite animation on component unmount + }; + }, []); +} +``` + + + +- You don't have to use `cancelAnimation` when the value is not animated. It will be garbage collected automatically when no more references to it exist. + + + +```javascript +const someFlag = makeMutable(false); + +function App() { + someFlag.value = true; // ✅ no need to cancel the animation later on +} +``` + + + +- When you decide to use `makeMutable`, ensure that you follow [Rules of React](https://react.dev/reference/rules) and avoid common `useRef` pitfalls, such as modifying the reference during rendering (see the **Pitfall** section in the [useRef](https://react.dev/reference/react/useRef) documentation for more details). + +### Comparison with `useSharedValue` + +| `makeMutable` | `useSharedValue` | +| ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| Creates a new object on each call | Reuses the same object on each call | +| If `initial` value changes, a new object with the new value is created | If `initialValue` value changes, the initially created object is returned without any changes | +| Can be used outside of the component scope | Can be used only inside the component scope | +| Can be used in loops (also when the number of iterations is not constant) | Can be used in loops only if the number of rendered hooks (`useSharedValue` calls) is constant | +| Doesn't automatically cancel animations when the component is unmounted | Automatically cancels animations when the component is unmounted | + +## Platform compatibility + +
+ +| Android | iOS | Web | +| ------- | --- | --- | +| ✅ | ✅ | ✅ | + +
diff --git a/packages/docs-reanimated/docs/core/useSharedValue.mdx b/packages/docs-reanimated/docs/core/useSharedValue.mdx index b386d45f418..e9eec0711c7 100644 --- a/packages/docs-reanimated/docs/core/useSharedValue.mdx +++ b/packages/docs-reanimated/docs/core/useSharedValue.mdx @@ -51,7 +51,7 @@ The value you want to be initially stored to a `.value` property. It can be any `useSharedValue` returns a shared value with a single `value` property initially set to the `initialValue`. -Values stored in shared values can be accessed and modified by their `.value` property. +Data stored in shared values can be accessed and modified by their `.value` property. ## Example diff --git a/packages/docs-reanimated/src/examples/MakeMutable.tsx b/packages/docs-reanimated/src/examples/MakeMutable.tsx new file mode 100644 index 00000000000..98d3fb32dc4 --- /dev/null +++ b/packages/docs-reanimated/src/examples/MakeMutable.tsx @@ -0,0 +1,174 @@ +import { + Text, + StyleSheet, + View, + TouchableOpacity, + useColorScheme, +} from 'react-native'; + +import React, { useCallback, useMemo, useState } from 'react'; +import Animated, { + makeMutable, + runOnJS, + runOnUI, + useAnimatedStyle, +} from 'react-native-reanimated'; +import type { SharedValue } from 'react-native-reanimated'; + +type CheckListSelectorProps = { + items: string[]; + onSubmit: (selectedItems: string[]) => void; +}; + +function CheckListSelector({ items, onSubmit }: CheckListSelectorProps) { + const checkListItemProps = useMemo( + () => + items.map((item) => ({ + item, + // highlight-next-line + selected: makeMutable(false), + })), + [items] + ); + + const handleSubmit = useCallback(() => { + runOnUI(() => { + const selectedItems = checkListItemProps + .filter((props) => props.selected.value) + .map((props) => props.item); + + runOnJS(onSubmit)(selectedItems); + })(); + }, [checkListItemProps, onSubmit]); + + return ( + + {checkListItemProps.map((props) => ( + + ))} + + Submit + + + ); +} + +type CheckListItemProps = { + item: string; + selected: SharedValue; +}; + +function CheckListItem({ item, selected }: CheckListItemProps) { + const scheme = useColorScheme(); + const onPress = useCallback(() => { + // highlight-start + // No need to update the array of selected items, just toggle + // the selected value thanks to separate shared values + runOnUI(() => { + selected.value = !selected.value; + })(); + // highlight-end + }, [selected]); + + return ( + + {/* highlight-start */} + {/* No need to use `useDerivedValue` hook to get the `selected` value */} + + {/* highlight-end */} + + {item} + + + ); +} + +type CheckBoxProps = { + value: SharedValue; +}; + +function CheckBox({ value }: CheckBoxProps) { + const checkboxTickStyle = useAnimatedStyle(() => ({ + opacity: value.value ? 1 : 0, + })); + + return ( + + + + ); +} + +const ITEMS = [ + '🐈 Cat', + '🐕 Dog', + '🦆 Duck', + '🐇 Rabbit', + '🐁 Mouse', + '🐓 Rooster', +]; + +export default function App() { + const [selectedItems, setSelectedItems] = useState([]); + const scheme = useColorScheme(); + + return ( + + + + Selected items:{' '} + {selectedItems.length ? selectedItems.join(', ') : 'None'} + + + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + }, + checkList: { + gap: 8, + padding: 16, + }, + listItem: { + flexDirection: 'row', + alignItems: 'center', + gap: 12, + }, + listItemText: { + fontSize: 20, + }, + checkBox: { + width: 16, + height: 16, + borderRadius: 4, + borderWidth: 1, + padding: 2, + borderColor: '#b58df1', + }, + checkBoxTick: { + flex: 1, + borderRadius: 2, + backgroundColor: '#b58df1', + }, + submitButton: { + backgroundColor: '#b58df1', + color: 'white', + alignItems: 'center', + borderRadius: 4, + padding: 8, + marginTop: 16, + }, + submitButtonText: { + color: 'white', + fontSize: 16, + fontWeight: 'bold', + }, +});