Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

291
Visualizações
Is there any other easy way to get the height and width of a container using React Hooks?

I'm using React hooks useEffect to get the width and height of the container. The problems I want to solve are:

  1. I want to get the responsive container height/width and not the window height/width.
  2. My Initial state is set to window.innerHeight and this itself crashes my output on the Initial render as I'm using the dimension state to get something done in the first place.
  3. I want to use the latest methods which are much simpler.. may be useRef() or anything..

I'm new to this React Hooks and unaware of many things.. I want simple code which perfectly does the work.

My code is as below:

function debounce(fn, ms) {
    let timer;
    return (_) => {
        clearTimeout(timer);
        timer = setTimeout((_) => {
            timer = null;
            fn.apply(this, arguments);
        }, ms);
    };
}

export default function App() {
    const [dimensions, setDimensions] = useState({
        height: window.innerHeight,
        width: window.innerWidth,
    });

    useEffect(() => {
        const debouncedHandleResize = debounce(function handleResize() {
            setDimensions({
                height: window.innerHeight,
                width: window.innerWidth,
            });
        }, 1000);

        document
            .getElementById('SldBox')
            .addEventListener('resize', debouncedHandleResize);

        return (_) => {
            document
                .getElementById('SldBox')
                .removeEventListener('resize', debouncedHandleResize);
        };
    });

    return (
        <div className='container' id='SldBox'>
            My Container
        </div>
    );
}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Cool problem, lots of hooks to be learned here.

Here is a sample of how we can use:

  • useState
  • useEffect
  • useMemo
  • useRef

https://codesandbox.io/s/keen-poincare-c8mcz?file=/src/App.js

useState: You've made good use of this one. No need to explain it more.

useRef: Create a ref then pass it to your element.

export default function App() {
  const ref = useRef(null);

  return (
    <div ref={ref}>stuff</div>
  );
}

Now after the first render, we can reference the element easily enough.

useMemo: To set up an observer for an element we can use ResizeObserver. If we didn't wrap this in useMemo, we would be recreating this function on every render which is wasteful. useMemo remedies this. We also add a dependency array for useMemo as the second argument that includes ref.current. This way, anytime ref changes (like on the first render), the elementObserver function will be recalculated.

  const elementObserver = useMemo(() => {
    return new ResizeObserver(() => {
      debounce(() => {
        if (!ref.current) return;
        setDimensions({
          height: ref.current.clientHeight,
          width: ref.current.clientWidth
        });
      }, 1000)();
    });
  }, [ref.current]);

useEffect: Now we can just use useEffect to set the observer when the component mounts. Again we include a dependency array that tells the effect to trigger the callback function provided if any of these values are changed. It will also always run when the component mounts, so we need to check ref exists for this one. Also, assign the element to a variable in the effect for the "cleanup" function.

  useEffect(() => {
    if (!ref) return;
    const element = ref.current;

    elementObserver.observe(element);
    return () => {
      elementObserver.unobserve(element);
    };
  }, [ref.current, elementObserver]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda