This is the dev preview website. Check out the document at lynxjs.org

Home > @lynx-js/react > useMainThreadRef

useMainThreadRef() function

Create A MainThreadRef.

A MainThreadRef is a ref that can only be accessed on the main thread. It is used to preserve states between main thread function calls. The data saved in current property of the MainThreadRef can be read and written in multiple main thread functions.

It is a hook and it should only be called at the top level of your component.

Signature:

export declare function useMainThreadRef<T>(initValue: T): MainThreadRef<T>;

Parameters

Parameter

Type

Description

initValue

T

The init value of the MainThreadRef.

Returns:

MainThreadRef<T>

Example

import { useMainThreadRef } from '@lynx-js/react'
import type { MainThread } from '@lynx-js/types'

export function App() {
  const ref = useMainThreadRef<MainThread.Element>(null)

  const handleTap = () => {
    'main thread'
    ref.current?.setStyleProperty('background-color', 'blue')
  }

  return (
    <view
      main-thread:ref={ref}
      main-thread:bindtap={handleTap}
      style={{ width: '300px', height: '300px' }}
    />
  )
}