Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created July 18, 2020 14:29
Show Gist options
  • Save karol-majewski/34a34c7b0e3350b52ab02132e39826b0 to your computer and use it in GitHub Desktop.
Save karol-majewski/34a34c7b0e3350b52ab02132e39826b0 to your computer and use it in GitHub Desktop.
Using React Hooks inside class components with TypeScript
import * as React from 'react';
import { useIdle } from 'react-use';
interface Props {
timeoutMs: number;
children: (data: boolean) => React.ReactElement | null;
}
const IdleStateRecognition: React.FunctionComponent<Props> = ({ children, timeoutMs }) => {
const isIdle = useIdle(timeoutMs);
return children(isIdle);
}
@karol-majewski
Copy link
Author

Usage:

const ONE_MINUTE_IN_MILLISECONDS = 60 * 10e3;

class MyLegacyClassComponent extends React.Component {
  render() {
    return (
      <IdleStateRecognition timeoutMs={ONE_MINUTE_IN_MILLISECONDS}>
        {isIdle => {
          if (isIdle) {
            return <div>Stopped due to inactivity.</div>
          }

          return <ComputationallyExpensiveComponent />
        }
        }
      </IdleStateRecognition>
    )
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment