[英]Custom React Hooks and what to keep inside useEffect hook
I have the following code and I wonder how I can improve performance, specifically, should I move the const fuse = new Fuse...
section and the buildSearchRequest
function within useEffect so it is called only when the search query is changed?我有以下代码,我想知道如何提高性能,具体来说,我应该移动
const fuse = new Fuse...
部分和buildSearchRequest
中的 buildSearchRequest function 以便仅在更改搜索查询时调用它? I have noticed my code that consumes the custom hooks hits the new Fuse
section many times.我注意到我的使用自定义钩子的代码多次点击
new Fuse
部分。
const [searchResults, setSearchResults] = React.useState([])
const fuse = new Fuse(DummySearchResponse.results, {
keys: ["data.programmeTitle"],
includeScore: true,
threshold: 0.2,
})
const searchApiUrlStart = "http://mimir.prd.oasvc.itv.com/search?query="
const searchApiUrlEnd =
"&entityType=programme&streamingPlatform=itv_hub&checkAvailability=true"
const buildSearchRequest = (searchString) => {
return (
searchApiUrlStart +
encodeURIComponent(searchString) +
searchApiUrlEnd
)
}
React.useEffect(() => {
if (!query) return
const fetchData = async () => {
let searchData
if (useLiveSearchApi) {
const liveResponse = await fetch(
"http://mimir.prd.oasvc.itv.com/search?query=" +
buildSearchRequest(query) +
"&entityType=programme&streamingPlatform=itv_hub&checkAvailability=true"
)
const liveJson = await liveResponse.json()
const liveResults = await liveJson.results
searchData = liveResults
} else {
const fuseResponse = await fuse.search(query)
const fuseJson = await fuseResponse.map((result) => {
return result.item
})
searchData = fuseJson
}
const mappedResults = await searchData.map((searchItem) => ({
title: searchItem.data.programmeTitle,
contentImageUrl: searchItem.data.imageHref,
programmeCCId: searchItem.data.programmeCCId,
episodeId: searchItem.data.episodeId,
}))
setSearchResults(mappedResults)
}
fetchData()
}, [query])
return { searchResults }
}```
First and foremost, avoid declaring a callback within the useEffect.首先,避免在 useEffect 中声明回调。 What you need to do is use the useCallBack hook to declare your fetchData callBack
您需要做的是使用 useCallBack 挂钩来声明您的 fetchData callBack
Your code should atleast look like...你的代码至少应该看起来像......
const fetchData = useCallBack(() => {
// Your Fetch Data Code
}, [<dependency array>]) // Here, you want to add all dependencies whose current state you need. Note that if a dependency is not added here, and you use it within the useCallBack, you'll only access a stale state (state during initialization), and never the updated dependency state.
// Here are three ways you can declare your useEffect
useEffect(fetchData, [query]); You probably wanna use this one. Less lines and much cleaner.
useEffect(() => fetchData(), [query]);
useEffect(() => {
fetchData();
}, [query]);
Your useEffect will only be called once the query
variable has been updated.只有在更新
query
变量后才会调用您的 useEffect。 So, to ensure a sideEffect is not triggered, ensure your useEffect or the useCallBack specified as the trigger does not update the variable.因此,为确保不触发 sideEffect,请确保您的 useEffect 或指定为触发器的 useCallBack 不会更新变量。 If this is the case, your code will be stuck in an indefinite loop.
如果是这种情况,您的代码将陷入无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.