useValue
The useValue()
function is a powerful hook designed to manage and animate values within your React components without triggering unnecessary re-renders. It behaves similarly to a ref, holding the current animation state internally.
This hook returns a tuple: [value, setValue]
.
- value: The current animated state, which you can directly apply to JSX styles or component props.
- setValue: A function to update the
value
, which can trigger a smooth animation when used with motion modifiers.
Basic Usage
The primary use case for useValue()
is to animate properties. For instance, to animate an element's width:
When you assign a raw value (e.g., setWidth(200)
), the property changes immediately without animation. To achieve a smooth transition, you must wrap the target value in a animation modifier like (withTiming or withSpring).
Usage
1. Primitive Values (Number & String)
For primitive data types such as numbers or strings, useValue
manages a single animated value directly.
Syntax
const [value, setValue] = useValue(initialValue: number | string);
View example
2. Array of Primitives
You can also animate an array of values. The hook stores the array and you update it similarly:
Syntax
const [arr, setArr] = useValue(initialArray: number[]);
View example
3. Object of Primitives
You can also initialize useValue with an object whose fields are numbers or strings. The hook returns a matching object
Syntax
const [obj, setObj] = useValue(initialObject: { [key: string]: number | string });