React Hooks & Custom Hooks
// reusable custom hooks
function useVar(type = `A`) {
let var = `var${type}`;
let setVar = `setVar${type}`;
// re-declared bug
const [var, setVar] = useState(0);
useEffect(() => {
const timeout = setTimeout(() => setVar(var + 1), 1000);
return () => clearTimeout(timeout);
}, [var]);
return [var, setVar];
}
// function aruments
function useVarX(init = 0, time = 1000, name = `varX`) {
const [varX, setVarX] = useState(init);
useEffect(() => {
const timeout = setTimeout(() => setVarX(varX + 1), time);
return () => clearTimeout(timeout);
}, [varX, time]);
return [varX, name, setVarX];
// return [varX, setVarX];
}
https://codesandbox.io/s/react-custom-hooks-with-arguments-2848r
This expression is not callable.
Not all constituents of type 'string | number | Dispatch
Type 'string' has no call signatures.ts(2349)
function App() {
const [varA, setVarA] = useVarA();
const [varB, setVarB] = useVarB();
return (
<span>
Var A: {varA}, Var B: {varB}
</span>
);
}
//
function useVarA() {
const [varA, setVarA] = useState(0);
useEffect(() => {
const timeout = setTimeout(() => setVarA(varA + 1), 1000);
return () => clearTimeout(timeout);
}, [varA]);
return [varA, setVarA];
}
function useVarB() {
const [varB, setVarB] = useState(0);
useEffect(() => {
const timeout = setTimeout(() => setVarB(varB + 2), 2000);
return () => clearTimeout(timeout);
}, [varB]);
return [varB, setVarB];
}
https://medium.com/swlh/useeffect-4-tips-every-developer-should-know-54b188b14d9c
https://blog.bitsrc.io/writing-your-own-custom-hooks-4fbcf77e112e
https://dev.to/wellpaidgeek/how-to-write-custom-hooks-in-react-1ana
https://dev.to/patrixr/react-writing-a-custom-api-hook-l16
https://reactjs.org/docs/hooks-custom.html
https://reactjs.org/docs/hooks-rules.html
xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
手机扫一扫
移动阅读更方便
你可能感兴趣的文章