Skip to main navigationSkip to main content
Return to Sky UI homepage

hooks - useIntersection

import { useIntersection } from '@sky-uk/ui-core';

The useIntersection hook can be used to determine whether or not a component is intersecting with the viewport. The optional options object allows you to controls when the observer's callback function is invoked. See MDN

function Example() {
  const ref = React.useRef();
  const [content, setContent] = React.useState('Threshold not reached');

  const  { intersecting} = useIntersection({
    ref,
    intersectionOptions: {
      threshold: 0.5
    }
  })

  React.useEffect(() => {
    if (intersecting) {
      setContent('Threshold reached');
      return;
    }
    setContent('Threshold not reached');
  }, [intersecting])

  return (
    <Box $position="relative" $height="140vh">
      <Box $position="absolute" $top="calc(50% - 10vh)" ref={ref}>
        <Flex $flexDirection="column" $justifyContent="space-between" $height="20vh">
          <Text>{content}</Text>
          <Text>{content}</Text>
        </Flex>
      </Box>
    </Box>
  );
}