React re-rendering and sCU()
I talked here about adding IntersectionObserver to the index pages of the blog, and using a keyboard watcher to scroll between posts using the common J and K pattern. What I only noticed today is that I was re-rendering the page over and over for no reason.
I keep track of which posts are currently 'onscreen' by keeping the visible post's indexes in an array, in the component's React state. As posts scroll out of view, the state updates. Say [0, 1, 2] are visible; scroll down so that 0 goes off the top of the screen, and 3 comes in, now the state has an array of [1, 2, 3] in it.
React re-renders on every state change. In this case, unnecessarily. The posts don't change; if not for the Observer, it would be a totally static HTML page.
So, I finally found a reason to use
shouldComponentUpdate. By only returning true if the props have changed, and never just because the state has, the page only renders once. The state changes and the keypresses work, but there's no need to re-render the page.