diff --git a/README.md b/README.md index 921a928..8bc5d8e 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,21 @@ block([ }/> ``` +## `Animated.useCode` + +The `useCode` hook acts as an alternative to the `Animated.Code` component. +```js +Animated.useCode(node, deps) +``` +It's passed an animated node and an array of dependencies, and updates that node both when the component mounts and every time a value in that array changes. It does nothing on versions of React Native that don't support hooks (<0.59). +```js +const [offset, setOffset] = React.useState(20); +Animated.useCode( + set(transX1, add(_transX, offset)), + [offset] +); +``` + ## Event handling with reanimated nodes `react-native-reanimated`'s new syntax is possible to be used with `Animated.event`. Instead of providing only a mapping from event fields to animated nodes, it is allowed to write a function that takes reanimated values map as an input and return a block (or any other reanimated function) that will be then used to handle the event. diff --git a/react-native-reanimated.d.ts b/react-native-reanimated.d.ts index 055d111..b1a0886 100644 --- a/react-native-reanimated.d.ts +++ b/react-native-reanimated.d.ts @@ -278,6 +278,12 @@ declare module 'react-native-reanimated' { config: DecayConfig, ): BackwardCompatibleWrapper; + // hooks + export function useCode( + exec: AnimatedNode, + deps: Array, + ): void + // configuration // `addWhitelistedNativeProps` will likely be removed soon, and so is diff --git a/src/derived/index.js b/src/derived/index.js index 701fa15..1ef5e5c 100644 --- a/src/derived/index.js +++ b/src/derived/index.js @@ -9,3 +9,4 @@ export { default as min } from './min'; export { default as onChange } from './onChange'; export { default as floor } from './floor'; export { default as ceil } from './ceil'; +export { default as useCode } from './useCode'; diff --git a/src/derived/useCode.js b/src/derived/useCode.js new file mode 100644 index 0000000..1517986 --- /dev/null +++ b/src/derived/useCode.js @@ -0,0 +1,15 @@ +import React from 'react'; +import { always } from '../base'; + +function useCode(exec, deps) { + if (typeof React.useEffect === 'function') { + React.useEffect(() => { + const animatedAlways = always(exec); + animatedAlways.__attach(); + return () => { + animatedAlways.__detach(); + }; + }, deps); + } +} +export default useCode;