Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active September 25, 2020 10:15
Show Gist options
  • Select an option

  • Save loilo/e62e26b1c1f1e1a23c30b43463ae0b77 to your computer and use it in GitHub Desktop.

Select an option

Save loilo/e62e26b1c1f1e1a23c30b43463ae0b77 to your computer and use it in GitHub Desktop.
useTerminalSize() React Hook
import { useEffect, useState } from 'react'
/**
* React hook which provides the size of the terminal, based on https://usehooks.com/useWindowSize/
* Great for usage with Ink (https://npmjs.com/package/ink)
*/
export function useTerminalSize() {
const [terminalSize, setTerminalSize] = useState([
process.stdout.columns,
process.stdout.rows
])
useEffect(() => {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
setTerminalSize([
process.stdout.columns,
process.stdout.rows
])
}
// Add event listener
process.stdout.on('resize', handleResize)
// Remove event listener on cleanup
return () => {
process.stdout.off('resize', handleResize)
}
}, []) // Empty array ensures that effect is only run on mount
return terminalSize
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment