Skip to content

Memoize ref function #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion karma.conf.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
process.env.CHROME_BIN = require('puppeteer').executablePath()

module.exports = function(config) {
module.exports = function (config) {
config.set({
frameworks: ['mocha'],

Expand All @@ -20,6 +20,10 @@ module.exports = function(config) {
webpack: {
mode: 'development',
devtool: 'inline-source-map',
node: {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests fail with module fs and module not defined error

fs: 'empty',
module: 'empty',
},
module: {
rules: [
{
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@
"@babel/preset-typescript": "^7.10.1",
"@babel/register": "^7.10.1",
"@testing-library/react": "^10.2.1",
"@testing-library/react-hooks": "^3.4.2",
"@types/debounce": "^1.2.0",
"@types/expect": "^24.3.0",
"@types/lodash-es": "^4.17.3",
"@types/mocha": "^7.0.2",
"@types/react": "^16.9.35",
Expand Down Expand Up @@ -91,6 +91,7 @@
"puppeteer": "^3.3.0",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-test-renderer": "^17.0.1",
"resize-observer-polyfill": "^1.5.1",
"rimraf": "^3.0.2",
"rollup": "^2.13.1",
Expand Down
27 changes: 23 additions & 4 deletions src/web/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as React from 'react'
import styled, { createGlobalStyle } from 'styled-components'
import expect from 'expect'
import { render, cleanup, RenderResult, fireEvent } from '@testing-library/react'
import { renderHook } from '@testing-library/react-hooks'
import Polyfill from 'resize-observer-polyfill'

import useMeasure, { Options } from '.'
Expand All @@ -27,8 +28,8 @@ const Wrapper = styled.div`
`

const Box = styled.div<{ big: boolean }>`
width: ${p => (p.big ? 400 : 200)}px;
height: ${p => (p.big ? 400 : 200)}px;
width: ${(p) => (p.big ? 400 : 200)}px;
height: ${(p) => (p.big ? 400 : 200)}px;
overflow: hidden;
font-size: 8px;
`
Expand All @@ -38,8 +39,8 @@ const Box = styled.div<{ big: boolean }>`
*/

const getBounds = (tools: RenderResult): ClientRect => JSON.parse(tools.getByTestId('box').innerHTML)
const nextFrame = () => new Promise(resolve => setTimeout(resolve, 1000 / 60))
const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
const nextFrame = () => new Promise((resolve) => setTimeout(resolve, 1000 / 60))
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

function ignoreWindowErrors(test: () => void) {
const onErrorBackup = window.onerror
Expand Down Expand Up @@ -210,4 +211,22 @@ describe('useMeasure', () => {
})
;(window as any).ResizeObserver = RO
})

it('memoize ref function', () => {
const { result, rerender } = renderHook(() => useMeasure())
const ref = result.current[0]
rerender()
expect(ref).toBe(result.current[0])
})

it('create new ref function when prop changed', () => {
const { result, rerender } = renderHook(({ scroll }) => useMeasure({ scroll }), {
initialProps: {
scroll: false,
},
})
const ref = result.current[0]
rerender({ scroll: true })
expect(ref).not.toBe(result.current[0])
})
})
75 changes: 39 additions & 36 deletions src/web/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState, useRef, useMemo } from 'react'
import { useEffect, useState, useRef, useMemo, useCallback, MutableRefObject } from 'react'
import { debounce as createDebounce } from 'debounce'

declare type ResizeObserverCallback = (entries: any[], observer: ResizeObserver) => void
Expand Down Expand Up @@ -99,52 +99,30 @@ function useMeasure({ debounce, scroll, polyfill }: Options = { debounce: 0, scr
]
}, [set, scrollDebounce, resizeDebounce])

// cleanup current scroll-listeners / observers
function removeListeners() {
if (state.current.scrollContainers) {
state.current.scrollContainers.forEach((element) => element.removeEventListener('scroll', scrollChange, true))
state.current.scrollContainers = null
}

if (state.current.resizeObserver) {
state.current.resizeObserver.disconnect()
state.current.resizeObserver = null
}
}

// add scroll-listeners / observers
function addListeners() {
if (!state.current.element) return
state.current.resizeObserver = new ResizeObserver(scrollChange)
state.current.resizeObserver!.observe(state.current.element)
if (scroll && state.current.scrollContainers) {
state.current.scrollContainers.forEach((scrollContainer) =>
scrollContainer.addEventListener('scroll', scrollChange, { capture: true, passive: true })
)
}
}

// the ref we expose to the user
const ref = (node: HTMLOrSVGElement | null) => {
if (!node || node === state.current.element) return
removeListeners()
state.current.element = node
state.current.scrollContainers = findScrollContainers(node)
addListeners()
}
const ref = useCallback(
(node: HTMLOrSVGElement | null) => {
if (!node || node === state.current.element) return
removeListeners(state, scrollChange)
state.current.element = node
state.current.scrollContainers = findScrollContainers(node)
addListeners(state, scrollChange, scroll)
},
[scroll, scrollChange]
)

// add general event listeners
useOnWindowScroll(scrollChange, Boolean(scroll))
useOnWindowResize(resizeChange)

// respond to changes that are relevant for the listeners
useEffect(() => {
removeListeners()
addListeners()
removeListeners(state, scrollChange)
addListeners(state, scrollChange, scroll)
}, [scroll, scrollChange, resizeChange])

// remove all listeners when the components unmounts
useEffect(() => removeListeners, [])
useEffect(() => () => removeListeners(state, scrollChange), [])
return [ref, bounds, forceRefresh]
}

Expand Down Expand Up @@ -175,6 +153,31 @@ function findScrollContainers(element: HTMLOrSVGElement | null): HTMLOrSVGElemen
return [...result, ...findScrollContainers(element.parentElement)]
}

// cleanup current scroll-listeners / observers
function removeListeners(state: MutableRefObject<State>, scrollChange: () => void) {
if (state.current.scrollContainers) {
state.current.scrollContainers.forEach((element) => element.removeEventListener('scroll', scrollChange, true))
state.current.scrollContainers = null
}

if (state.current.resizeObserver) {
state.current.resizeObserver.disconnect()
state.current.resizeObserver = null
}
}

// add scroll-listeners / observers
function addListeners(state: MutableRefObject<State>, scrollChange: () => void, scroll?: boolean) {
if (!state.current.element) return
state.current.resizeObserver = new ResizeObserver(scrollChange)
state.current.resizeObserver!.observe(state.current.element)
if (scroll && state.current.scrollContainers) {
state.current.scrollContainers.forEach((scrollContainer) =>
scrollContainer.addEventListener('scroll', scrollChange, { capture: true, passive: true })
)
}
}

// Checks if element boundaries are equal
const keys: (keyof RectReadOnly)[] = ['x', 'y', 'top', 'bottom', 'left', 'right', 'width', 'height']
const areBoundsEqual = (a: RectReadOnly, b: RectReadOnly): boolean => keys.every((key) => a[key] === b[key])
Expand Down
Loading