File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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+ } )
You can’t perform that action at this time.
0 commit comments