Skip to content

Commit f876fd5

Browse files
authoredOct 10, 2021
Merge pull request #6 from lmichelin/typescript
Migrate to TypeScript
2 parents 87b2f55 + d1c18f0 commit f876fd5

File tree

4 files changed

+48
-19
lines changed

4 files changed

+48
-19
lines changed
 

‎index.js

-16
This file was deleted.

‎index.ts

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { useCallback, useRef, useState, SetStateAction, Dispatch } from "react";
2+
3+
const isFunction = <S>(setStateAction: SetStateAction<S>): setStateAction is (prevState: S) => S =>
4+
typeof setStateAction === "function";
5+
6+
type ReadOnlyRefObject<T> = {
7+
readonly current: T;
8+
};
9+
10+
type UseStateRef = {
11+
<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>, ReadOnlyRefObject<S>];
12+
<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>, ReadOnlyRefObject<S | undefined>];
13+
};
14+
15+
const useStateRef: UseStateRef = <S>(initialState?: S | (() => S)) => {
16+
const [state, setState] = useState(initialState);
17+
const ref = useRef(state);
18+
19+
const dispatch: typeof setState = useCallback(setStateAction => {
20+
ref.current = isFunction(setStateAction) ? setStateAction(ref.current) : setStateAction;
21+
22+
setState(ref.current);
23+
}, []);
24+
25+
return [state, dispatch, ref];
26+
};
27+
28+
export = useStateRef;

‎package.json

+12-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,13 @@
22
"name": "react-usestateref",
33
"version": "1.0.4",
44
"description": "useRef and UseState together!",
5-
"main": "index.js",
5+
"main": "dist/index.js",
6+
"files": [
7+
"dist"
8+
],
69
"scripts": {
7-
"deploy": "npm version patch && git add . && git commit && git push && npm publish"
10+
"build": "rimraf dist && tsc",
11+
"deploy": "npm run build && npm version patch && git push && npm publish"
812
},
913
"peerDependencies": {
1014
"react": ">16.0.0"
@@ -24,5 +28,10 @@
2428
"bugs": {
2529
"url": "https://github.com/Aminadav/react-useRefState/issues"
2630
},
27-
"homepage": "https://github.com/Aminadav/react-useRefState#readme"
31+
"homepage": "https://github.com/Aminadav/react-useRefState#readme",
32+
"devDependencies": {
33+
"@types/react": "^17.0.16",
34+
"rimraf": "^3.0.2",
35+
"typescript": "^4.3.5"
36+
}
2837
}

‎tsconfig.json

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"compilerOptions": {
3+
"strict": true,
4+
"lib": ["ES2015"],
5+
"outDir": "dist",
6+
"declaration": true
7+
}
8+
}

0 commit comments

Comments
 (0)