Skip to content

Files

Latest commit

6ef2c3d · Apr 4, 2021

History

History
49 lines (39 loc) · 1.58 KB

useRafLoop.md

File metadata and controls

49 lines (39 loc) · 1.58 KB

useRafLoop

This hook call given function within the RAF loop without re-rendering parent component. Loop stops automatically on component unmount.

Additionally hook provides methods to start/stop loop and check current state.

Usage

import { useRafLoop, useState } from 'vue-next-use';

const Demo = {
  setup(){
    const [ticks, setTicks] = useState(0);
    const [lastCall, setLastCall] = useState(0);

    const [loopStop, loopStart, isActive] = useRafLoop((time) => {
      setTicks(ticks => ticks + 1);
      setLastCall(time);
    });

    return () => (
        <div>
            <div>RAF triggered: {ticks.value} (times)</div>
            <div>Last high res timestamp: {lastCall.value}</div>
            <br />
            <button onClick={() => {
                isActive.value ? loopStop() : loopStart();
            }}>{isActive.value ? 'STOP' : 'START'}</button>
        </div>
    );
  }
};

Reference

const [stopLoop, startLoop, isActive] = useRafLoop(callback: FrameRequestCallback, initiallyActive = true);
  • callback: (time: number)=>void — function to call each RAF tick.
    • time: number — DOMHighResTimeStamp, which indicates the current time (based on the number of milliseconds since time origin).
  • initiallyActive: boolean — whether loop should be started at initial render.
  • Return
    • stopLoop: ()=>void — stop loop if it is active.
    • startLoop: ()=>void — start loop if it was inactive.
    • isActive: ComputedRef<boolean>true if loop is active.