Skip to content
This repository has been archived by the owner on Sep 18, 2024. It is now read-only.

Commit

Permalink
added useStateAsMotion hook
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiaaas committed Apr 6, 2021
1 parent 689b0f2 commit 5453489
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,24 @@ const MyComponent = () => {

- `state`: React state
- `value`: Motion value

### `useStateAsMotion`

Returns a MotionValue value that updates when the React state changes

```jsx
const MyComponent = () => {
const [opacity, setOpacity] = useState(0)

const motionOpacity = useStateAsMotion(opacity)

return <motion.div style={{ opacity: motionOpacity }} />
}
```

#### API

`const value = useStateAsMotion(state)`

- `value`: Motion value
- `state`: React state
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { useInViewAnimate } from "./useInViewAnimate"
export { useInViewScroll } from "./useInViewScroll"
export { useMotionAsState } from "./useMotionAsState"
export { useStateAsMotion } from "./useStateAsMotion"
17 changes: 17 additions & 0 deletions src/hooks/useStateAsMotion.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useEffect } from "react"
import { useMotionValue } from "framer-motion"

/**
* `useStateAsMotion` returns a MotionValue that updates when the React state changes
*
* @param state - React state
*/
export const useStateAsMotion = (state: any) => {
const motionValue = useMotionValue(state)

useEffect(() => {
motionValue.set(state)
}, [state])

return motionValue
}
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export { useInViewAnimate, useInViewScroll, useMotionAsState } from "./hooks"
export {
useInViewAnimate,
useInViewScroll,
useMotionAsState,
useStateAsMotion
} from "./hooks"

0 comments on commit 5453489

Please sign in to comment.