# use-cannon
**Repository Path**: mirrors_developit/use-cannon
## Basic Information
- **Project Name**: use-cannon
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2020-08-08
- **Last Updated**: 2026-07-25
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README

yarn add use-cannon
Live demo: https://codesandbox.io/s/r3f-cannon-instanced-physics-g1s88
Experimental web-worker based React hooks for cannon (using [cannon-es](https://github.com/drcmda/cannon-es)) in combination with [react-three-fiber](https://github.com/react-spring/react-three-fiber). Right now it only supports planes and boxes, for individual objects or instanced objects. The public api can only set positions for now. If you need more, please submit your PRs.
How does it work? It subscribes the view part of a component to cannons physics world and unsubscribes on unmount. You don't put position/rotation/scale into the mesh any longer, you put it into the hook, which takes care of forwarding all movements.
Internally it communicates with the web worker via fixed-size array buffers, but it keeps track of how many physics based components you have mounted automatically and adjusts these buffers when needed.
```jsx
import * as THREE from 'three'
import ReactDOM from 'react-dom'
import React, { useMemo } from 'react'
import { Canvas, useFrame } from 'react-three-fiber'
import niceColors from 'nice-color-palettes'
import { useCannon, useCannonInstanced, Physics } from 'use-cannon'
function Plane({ position = [0, 0, 0], rotation = [0, 0, 0] }) {
const [ref, api] = useCannon({ mass: 0, type: 'Plane', position, rotation })
return (
)
}
function Cubes({ number }) {
const positions = useMemo(
() => new Array(number).fill().map(() => [Math.random() - 0.5, Math.random() * 2, Math.random() - 0.5]),
[number]
)
const [ref, api] = useCannonInstanced({ mass: 1, type: 'Box', args: [0.05, 0.05, 0.05], positions })
const colors = useMemo(() => {
const array = new Float32Array(number * 3)
const color = new THREE.Color()
for (let i = 0; i < number; i++) {
color.set(niceColors[17][Math.floor(Math.random() * 5)])
color.toArray(array, i * 3)
}
return array
}, [])
useFrame(() => api.setPosition(Math.floor(Math.random() * number), [0, Math.random() * 2, 0]))
return (
)
}
ReactDOM.render(
,
document.getElementById('root')
)
```