Skip to content

Commit f4c4753

Browse files
committed
feat: add useMountEffect
1 parent 31188e2 commit f4c4753

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/useMountEffect.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { useEffect, EffectCallback } from 'react'
2+
3+
/**
4+
* Run's an effect on mount, and is cleaned up on unmount. Generally
5+
* useful for interop with non-react plugins or components
6+
*
7+
* ```ts
8+
* useMountEffect(() => {
9+
* const plugin = $.myPlugin(ref.current)
10+
*
11+
* return () => {
12+
* plugin.destroy()
13+
* }
14+
* })
15+
* ```
16+
* @param effect An effect to run on mount
17+
*
18+
* @category effects
19+
*/
20+
function useMountEffect(effect: EffectCallback) {
21+
return useEffect(effect, [])
22+
}
23+
24+
export default useMountEffect

test/useMountEffect.test.tsx

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import useMountEffect from '../src/useMountEffect'
2+
import { renderHook } from './helpers'
3+
4+
describe('useMountEffect', () => {
5+
it('should run update only on mount', () => {
6+
const teardown = jest.fn()
7+
const spy = jest.fn(() => teardown)
8+
9+
const [, wrapper] = renderHook(
10+
() => {
11+
useMountEffect(spy)
12+
},
13+
{ value: 1, other: false },
14+
)
15+
16+
expect(spy).toHaveBeenCalledTimes(1)
17+
18+
wrapper.setProps({ value: 2 })
19+
20+
expect(spy).toHaveBeenCalledTimes(1)
21+
22+
wrapper.setProps({ value: 2, other: true })
23+
24+
expect(spy).toHaveBeenCalledTimes(1)
25+
26+
wrapper.unmount()
27+
28+
expect(teardown).toHaveBeenCalledTimes(1)
29+
})
30+
})

0 commit comments

Comments
 (0)