how to create react custom hooks with arguments All In One
how to create react custom hooks with arguments All In One
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];
}
OK
// 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
TS bug
This expression is not callable.
Not all constituents of type 'string | number | Dispatch<SetStateAction
Type 'string' has no call signatures.ts(2349)
demos
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
refs
https://reactjs.org/docs/hooks-custom.html
https://reactjs.org/docs/hooks-rules.html
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13572234.html
未经授权禁止转载,违者必究!