Search code examples
reactjsscrollviewscrollbaruse-effectconsole.log

Why is the console coming out differently in useEffect?


I wanted to make sure that the scroll was located in the middle of the area in case of scrolling.


const scrollRef = useScroll(null);

useEffect(() => {
    const wrapper = scrollRef.current;
    console.dir(wrapper, 'wrapper');
    if (wrapper) {
      const hasScroll = wrapper.scrollHeight > wrapper.clientHeight;
      console.log(wrapper.scrollHeight, 'scrollheight');
      console.log(wrapper.clientHeight, 'clientHeight');
      if (hasScroll) {
        const scrollTop = (wrapper.scrollHeight - wrapper.clientHeight) / 2;
        wrapper.scrollTop = scrollTop;
      }
    }
  }, [isLoading]);

if (isLoading) {
    return (
      <TradeSection>
        <Loader />
      </TradeSection>
    );
  }

<Section>
  <TableHeader>
  <TableList ref={scrollRef}>
    <List />
    <CurrentPrice />
    <List />
  </TableList>
<Section>

This code works well in general. but sometime it doesnt't work According to my guess, if you refresh after the screen size changes, so i add console in useEffect

enter image description here enter image description here

why console.dir > scrollHeight is different result ? Why do you show different values in the same area?


Solution

  • Your useEffect is not updating when the current ref value changes. This means that your console log fires whenever isLoading updates, but does not capture the final value of scrollRef.current.

    Putting something inside a useEffect is only helpful if the useEffect can actually keep track of changes to that value. Unfortunately, that is not possible with useRef because an object ref does not notify your component about changes to the current ref value. For this use case, the correct hook is actually useCallback; see this React FAQ answer for an explanation and a somewhat similar example.