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

docs: makeMutable documentation and examples #6261

Merged
merged 19 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from 13 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
155 changes: 155 additions & 0 deletions packages/docs-reanimated/docs/core/makeMutable.mdx
MatiPl01 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
---
sidebar_position: 8
---

# 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.

:::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.
MatiPl01 marked this conversation as resolved.
Show resolved Hide resolved
:::

## Reference

```javascript
import { makeMutable } from 'react-native-reanimated';

const mv = makeMutable(100);
```

<details>
<summary>Type definitions</summary>

```typescript
interface SharedValue<Value = unknown> {
value: Value;
addListener: (listenerID: number, listener: (value: Value) => void) => void;
removeListener: (listenerID: number) => void;
modify: (
modifier?: <T extends Value>(value: T) => T,
forceUpdate?: boolean
) => void;
}

function makeMutable<Value>(initial: Value): SharedValue<Value>;
```

</details>

### 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`.

Values stored in mutable values can be accessed and modified by their `.value` property.
MatiPl01 marked this conversation as resolved.
Show resolved Hide resolved

## Example

import MakeMutable from '@site/src/examples/MakeMutable';
import MakeMutableSrc from '!!raw-loader!@site/src/examples/MakeMutable';

<InteractiveExample src={MakeMutableSrc} component={MakeMutable} showCode />

## Remarks
MatiPl01 marked this conversation as resolved.
Show resolved Hide resolved

- All remarks from the [useSharedValue](/docs/core/useSharedValue) hook apply to `makeMutable` as well.

- Don't use `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.
MatiPl01 marked this conversation as resolved.
Show resolved Hide resolved

<Indent>

```javascript
function App() {
const [counter, setCounter] = useState(0);
const mv = makeMutable(counter); // creates a new mutable value on each render
MatiPl01 marked this conversation as resolved.
Show resolved Hide resolved

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, ...
}
);
}
```

</Indent>

- 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.

<Indent>

```javascript
function App() {
const mv = useMemo(() => makeMutable(0), []);

useEffect(() => {
mv.value = withRepeat(withSpring(100), -1, true); // this creates an infinite animation

return () => {
cancelAnimation(mv); // this will stop the infinite animation when the component is unmounted
};
}, []);
}
```

</Indent>

- 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.

<Indent>

```javascript
const someFlag = makeMutable(false);

function App() {
someFlag.value = true; // no need to cancel the animation later on
}
```

</Indent>

### 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

<div className="platform-compatibility">

| Android | iOS | Web |
| ------- | --- | --- |
| ✅ | ✅ | ✅ |

</div>
174 changes: 174 additions & 0 deletions packages/docs-reanimated/src/examples/MakeMutable.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<View style={styles.checkList}>
{checkListItemProps.map((props) => (
<CheckListItem key={props.item} {...props} />
))}
<TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
<Text style={styles.submitButtonText}>Submit</Text>
</TouchableOpacity>
</View>
);
}

type CheckListItemProps = {
item: string;
selected: SharedValue<boolean>;
};

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 (
<TouchableOpacity style={styles.listItem} onPress={onPress}>
{/* highlight-start */}
{/* No need to use `useDerivedValue` hook to get the `selected` value */}
<CheckBox value={selected} />
{/* highlight-end */}
<Text
style={[
styles.listItemText,
{ color: scheme === 'dark' ? 'white' : 'black' },
]}>
{item}
</Text>
</TouchableOpacity>
);
}

type CheckBoxProps = {
value: SharedValue<boolean>;
};

function CheckBox({ value }: CheckBoxProps) {
const checkboxTickStyle = useAnimatedStyle(() => ({
opacity: value.value ? 1 : 0,
}));

return (
<View style={styles.checkBox}>
<Animated.View style={[styles.checkBoxTick, checkboxTickStyle]} />
</View>
);
}

const ITEMS = [
'🐈 Cat',
'🐕 Dog',
'🦆 Duck',
'🐇 Rabbit',
'🐁 Mouse',
'🐓 Rooster',
];

export default function App() {
const [selectedItems, setSelectedItems] = useState<string[]>([]);
const scheme = useColorScheme();

return (
<View style={styles.container}>
<CheckListSelector items={ITEMS} onSubmit={setSelectedItems} />
<Text style={{ color: scheme === 'dark' ? 'white' : 'black' }}>
Selected items:{' '}
{selectedItems.length ? selectedItems.join(', ') : 'None'}
</Text>
</View>
);
}

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',
},
});