useSharedValue
- React Native course
- Advanced
- Lesson 62/83
- 5 min
Learn shared values with useSharedValue.
useSharedValue
useSharedValue creates a value shared between the UI and JS threads. This value is the base state of the animation. Example: const offset = useSharedValue(0). The value starts at 0; later you can change it with offset.value = 100.
Important distinction: the value is read and written via the offset.value property; not directly as offset = 100. Because offset is an object, .value is the actual number inside. The UI thread watches this value; every change triggers an animation.
Changing the value
To change the shared value you assign to the .value property. Example: offset.value = 100. This assignment informs the UI thread; if an animated style depends on this value, the style is recalculated.
To add an animation you write offset.value = withTiming(100). Here withTiming does not jump to 100 instantly; it goes linearly within a fixed duration. This provides a smooth transition unlike a plain assignment. Choosing the animation type sets the feel.
Practice Define a shared value
Import useSharedValue from react-native-reanimated. Define a shared value with const offset = useSharedValue(0). Assign offset.value = 100.
Starter code
import React from 'react';
export function useOffset() {
// define offset and assign 100
return offset;
}Sample solution
import React from 'react';
import { useSharedValue } from 'react-native-reanimated';
export function useOffset() {
const offset = useSharedValue(0);
offset.value = 100;
return offset;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the useSharedValue parts
| Term | Meaning |
|---|---|
useSharedValue |
Hook |
0 |
Initial value |
.value |
Number property |
UI thread |
Watches the value |
2 Why use .value?
- Because useSharedValue returns an object
- Because Animated is unnecessary
- Because numbers cannot be written Correct answer
- Because hooks cannot be used
Explanation: useSharedValue returns an object; .value accesses the number.
3 The value assignment
const offset = useSharedValue(0);
offset.____ = 100;
const offset = useSharedValue(0);
offset.value = 100;
Explanation: The .value property carries the number.