betula / use-between

Sharing state between React components
MIT License
285 stars 11 forks source link

How to use with useRef? #45

Open mtnair opened 10 months ago

mtnair commented 10 months ago

See following simple example code:

'use client';

import { useRef } from 'react';
import { Toast } from 'primereact/toast';
import { useBetween } from 'use-between';

export const useSharedToast = () => useBetween(useRef<Toast>);

export default function RootLayout({ children }: { children: React.ReactNode }) {
  const toast = useSharedToast();

  return (
    <html lang='de'>
      <body>
        {children}
        <Toast ref={toast} />
      </body>
    </html>
  );
}

This gives me the error: Type 'MutableRefObject<Toast | undefined>' is not assignable to type 'LegacyRef<Toast> | undefined'. I know I should initialize useRef with null, but I don't know how to do that with useBetween. I didn't find any examples with useRef, though it's listed as a supported hook.

How can I do this?

melloware commented 8 months ago

I think your useRef has to be null like React.useRef(null) else it thinks you have a legacy ref