Skip to content

Commit 8e8ffa6

Browse files
committed
Add minimal log hook
1 parent 0ee999a commit 8e8ffa6

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

demo/App.tsx

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,39 @@
1-
import React from 'react'
1+
import React, { useEffect, useState } from 'react'
2+
import { useLog } from '../src'
3+
4+
const ExampleComponent = (): React.ReactElement => {
5+
const { log } = useLog()
6+
const [state, setState] = useState<string | null>(null)
7+
8+
log(state)
9+
10+
useEffect(() => {
11+
setState('onMount')
12+
13+
setTimeout(() => {
14+
setState('onChange 1s')
15+
}, 1000)
16+
17+
setTimeout(() => {
18+
setState('onChange 2s')
19+
}, 2000)
20+
}, [])
21+
22+
return <p>Test Component: {state}</p>
23+
}
224

325
const App = (): React.ReactElement => {
26+
const [isExampleMounted, setIsExampleMounted] = useState<boolean>(true)
27+
28+
setTimeout(() => {
29+
setIsExampleMounted(false)
30+
}, 3000)
31+
432
return (
533
<div>
634
<p>Demo for React log hook.</p>
735
<p>Please check the console for logs.</p>
36+
{isExampleMounted ? <ExampleComponent /> : null}
837
</div>
938
)
1039
}

src/index.tsx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { useEffect } from 'react'
2+
3+
export interface UseLogReturn {
4+
log: <T>(value: T) => void
5+
}
6+
7+
export const useLog = (): UseLogReturn => {
8+
function log<T>(value: T): void {
9+
return (() => {
10+
useEffect(() => {
11+
console.log(`On mount: ${String(value)}`)
12+
13+
return () => {
14+
console.log(`On unmount: ${String(value)}`)
15+
}
16+
}, [])
17+
18+
useEffect(() => {
19+
console.log(`On change: ${String(value)}`)
20+
}, [value])
21+
})()
22+
}
23+
24+
return { log }
25+
}

0 commit comments

Comments
 (0)