Skip to content
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

feat: setting react package and create useInterval #13

Merged
merged 14 commits into from
Jun 3, 2024
Merged
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"ci:version": "changeset version",
"logging-system": "pnpm --filter @yourssu/logging-system-react",
"utils": "pnpm --filter @yourssu/utils",
"react": "pnpm --filter @yourssu/react",
"prepare": "husky",
"test": "vitest",
"test:ui": "vitest --ui"
Expand Down
Empty file added packages/react/README.md
Empty file.
39 changes: 39 additions & 0 deletions packages/react/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "@yourssu/react",
"private": false,
"version": "0.1.0",
"description": "Yourssu React Package",
"keywords": [
"yourssu",
"react"
],
"repository": {
"type": "git",
"url": "https://github.com/yourssu/Yrano",
"directory": "packages/react"
},
"license": "MIT",
"type": "module",
"types": "./dist/index.d.ts",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"scripts": {
"build": "tsc && tsup",
"test": "vitest"
},
"devDependencies": {
"@testing-library/react": "^15.0.7"
}
}
27 changes: 27 additions & 0 deletions packages/react/src/hooks/useInterval.ko.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# useInterval

`useInterval` 커스텀 훅은 특정 간격마다 주어진 콜백 함수를 실행하기 위해 사용됩니다. 이 훅은 `useEffect`와 `useRef`를 활용하여 콜백 함수와 간격 타이머를 관리합니다.

## 매개변수

- `callback`: 실행될 콜백 함수입니다.
- `interval`: 콜백 함수가 실행될 간격(밀리초)입니다.

## Example

```jsx
const MyComponent = () => {
useInterval(() => {
console.log('This will run every second');
}, 1000);

return <div>Check the console</div>;
};
```

## Notes
이 훅은 내부적으로 두 개의 `useEffect`를 사용합니다:
1. 첫 번째 `useEffect`는 콜백 함수를 최신 상태로 유지합니다.
2. 두 번째 `useEffect`는 주어진 간격마다 콜백 함수를 실행하는 타이머를 설정합니다.

`interval`이 변경되거나 `null`로 설정되면 타이머가 갱신되거나 해제됩니다.
79 changes: 79 additions & 0 deletions packages/react/src/hooks/useInterval.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { renderHook, act } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';

import { useInterval } from './useInterval'; // Adjust the import path to your actual useInterval hook

describe('useInterval', () => {
it('should call the callback function at the given interval', () => {
vi.useFakeTimers();

const callback = vi.fn();
const interval = 1000;

renderHook(() => useInterval(callback, interval));

expect(callback).not.toHaveBeenCalled();

act(() => {
vi.advanceTimersByTime(interval);
});

expect(callback).toHaveBeenCalledTimes(1);

act(() => {
vi.advanceTimersByTime(interval);
});

expect(callback).toHaveBeenCalledTimes(2);

vi.useRealTimers();
});

it('should not call the callback function when the interval is null', () => {
vi.useFakeTimers();

const callback = vi.fn();
const interval = null;

renderHook(() => useInterval(callback, interval as unknown as number));

expect(callback).not.toHaveBeenCalled();

act(() => {
vi.advanceTimersByTime(1000);
});

expect(callback).not.toHaveBeenCalled();

vi.useRealTimers();
});

it('should update the interval when the interval changes', () => {
vi.useFakeTimers();

const callback = vi.fn();
let interval = 1000;

const { rerender } = renderHook(() => useInterval(callback, interval));

expect(callback).not.toHaveBeenCalled();

act(() => {
vi.advanceTimersByTime(interval);
});

expect(callback).toHaveBeenCalledTimes(1);

interval = 2000;

rerender();

act(() => {
vi.advanceTimersByTime(interval);
});

expect(callback).toHaveBeenCalledTimes(2);

vi.useRealTimers();
});
});
38 changes: 38 additions & 0 deletions packages/react/src/hooks/useInterval.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { useEffect, useRef } from 'react';

interface UseIntervalProps {
(callback: () => void, interval: number): void;
}

/**
* `useInterval` 커스텀 훅은 특정 간격마다 주어진 콜백 함수를 실행합니다.
*
* @param {() => void} callback - 실행될 콜백 함수입니다.
* @param {number} interval - 콜백 함수가 실행될 간격(밀리초)입니다.
*
* @remarks
* 이 훅은 내부적으로 두 개의 `useEffect`를 사용합니다:
* 1. 첫 번째 `useEffect`는 콜백 함수를 최신 상태로 유지합니다.
* 2. 두 번째 `useEffect`는 주어진 간격마다 콜백 함수를 실행하는 타이머를 설정합니다.
*
* `interval`이 변경되거나 `null`로 설정되면 타이머가 갱신되거나 해제됩니다.
*/
export const useInterval: UseIntervalProps = (callback: () => void, interval: number) => {
const savedCallback = useRef<(() => void) | null>(null);

useEffect(() => {
savedCallback.current = callback;
}, [callback]);

useEffect(() => {
function tick() {
if (savedCallback.current) {
savedCallback.current();
}
}
if (interval !== null) {
const id = setInterval(tick, interval);
return () => clearInterval(id);
}
}, [interval]);
};
1 change: 1 addition & 0 deletions packages/react/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useInterval } from './hooks/useInterval.ts';
8 changes: 8 additions & 0 deletions packages/react/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist"
},
"include": ["src"]
}
18 changes: 18 additions & 0 deletions packages/react/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { defineConfig } from 'tsup';

export default defineConfig({
entry: ['./src/index.ts'],
format: ['cjs', 'esm'],
dts: {
entry: './src/index.ts',
resolve: true,
},
external: ['react', 'react-dom'],
splitting: false,
clean: true,
sourcemap: true,
minify: true,
treeshake: true,
skipNodeModulesBundle: true,
outDir: './dist',
});
9 changes: 9 additions & 0 deletions packages/react/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { defineConfig } from 'vitest/config';

export default defineConfig({
test: {
dir: './src',
globals: true,
environment: 'jsdom',
},
});
6 changes: 1 addition & 5 deletions packages/utils/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
"outDir": "./dist"
},
"include": ["src"]
}
76 changes: 76 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 0 additions & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},

/* Linting */
"strict": true,
Expand Down