'How to write React hooks with called functions?
I have a useQuery() hook:
const useQuery = () => {
const router = useRouter();
const build = (query) => {}
const read = () => {}
}
export default useQuery;
I want to be able to use hook in my code like:
const query = useQuery();
useEffect(()=>{
const oldQuery = query.read();
if(oldQuery.length === 0) query.build(newQuery);
},[])
but every time I try to call query.read() I get error Property 'read' does not exist on type 'void'. It looks like scope issue. How can I fix it?
Solution 1:[1]
You need a return statement in useQuery:
const useQuery = () => {
const router = useRouter();
const build = (query) => {}
const read = () => {}
return { router, build, read }
}
You may also want to consider memoizing these functions, so that code which consumes this hook doesn't do unnecessary work because it thinks the functions have changed:
const build = useCallback((query) => {}, []);
const read = useCallback((() => {}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicholas Tower |
