You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I recently stumbled about some code that looked like this:
exportconstuseSearch=(limit=10,offset=0)=>{const[query,setQuery]=React.useState("")const{ data }=useSWR(query.length>=3 ? [limit,offset,query] : null,()=>{returnsearch(query,limit,offset)})return{data: resultssetQuery}
I think there are 2 faults with this hook:
the query should be part of the hooks input arguments
(most important) the search function uses closures of limit, offset, query (in line 4) as they are not handed in to it via its own function arguments (in line 3)
What I think would happen if the useSearch hook would be called with different inputs (in a component based on incoming props) the search function would only ever be called with the very first inputs handed to the hook. Is my fear correct?
When the drop down triggers a change to limit to 20 via setLimit this could cause a re-render and the useSearch hook is called with the newly set limit. Would the result reflect the new limit of 20 or would it still be 10?
Also can give someone give me a hint how to compose a hook test to catch this error (if it is one)?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
I recently stumbled about some code that looked like this:
I think there are 2 faults with this hook:
search
function uses closures oflimit, offset, query
(in line 4) as they are not handed in to it via its own function arguments (in line 3)What I think would happen if the
useSearch
hook would be called with different inputs (in a component based on incoming props) thesearch
function would only ever be called with the very first inputs handed to the hook. Is my fear correct?Take this example:
When the drop down triggers a change to
limit
to 20 viasetLimit
this could cause a re-render and theuseSearch
hook is called with the newly setlimit
. Would theresult
reflect the new limit of 20 or would it still be 10?Also can give someone give me a hint how to compose a hook test to catch this error (if it is one)?
Beta Was this translation helpful? Give feedback.
All reactions