I have a custom hook that returns a value by parameters that it gets. I need to recreate this with any updated parameter so I need to do that inside useEffect but I can’t call the hook inside useEffect. How could I implement it?
The custom hook:
useApi.tsx
export default function useApi(id) {
const api = useGlobalApi()
const user = api.get(`..../${id}`)
...
return user
}
Api.tsx
export default function Api(id) {
const [user, setUser] = useState({})
const data = useApi(id)
useEffect(() => {
const user = useApi(id)
setUser(user)
}, [id])
...
}
I’m getting this error:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app`
How can I resolve this and get the expected result?
3
Answers
Return a memoized function (wrapped with
useCallback
) from the hook, and use that function in theuseEffect
.Custom hook:
Usage:
You can also get an immutable function, and pass the
id
in theuseEffect
:Usage:
then inside
Api.tsx
Your question is a bit confused because you are using 2 hooks called ‘useApi’, but I’ll try my best to help.
Since you are using a hook, you don’t need to call is again on useEffect.
Api.tsx
useApiCustom.tsx