Foreword
Recently in the development of new projects ts + hooks with these new features, the development of cutting-edge stuff is very silky feel wonderful, all the time stepped pit, unable to extricate themselves.
Problem Description
The directory structure something like this
--RtDetail
----Home
------index.scss
------index.tsx
----Search
------index.scss
------index.tsx
----Detail
------index.scss
------index.tsx
Then I introduced the Search and Detail components Home component, pseudo code something like this
/**
* Home.tsx 伪代码
* 大概就是引入了Search和Detail,给Search传入一个回调,当Search的输入框改变时候,触发更改Home中的searchId
*/
...
let Home = () => {
const [searchId, setSearchId] = useState(0)
const handleSearchIdChange = (e) => {
console.log('handleSearchChange 被创建了')
setSearchId(e.target.value)
}
return (
<>
<Search handleSearchId={handleSearchId}/>
<Detail />
</>
)
}
export default Home
/** Search.tsx 伪代码 */
...
let Search = (props: ISearchProps) => {
const { handleSearchId } = props
return (
<>
<input onChange={(e) => {handleSearchId(e)}}/>
</>
)
}
export default Search
...
/** Detail.tsx */
...
let Detail = () => {
console.log('Detail Component 被渲染了')
return (
<span>test</span>
)
}
export default Detail
...
Search Home Every change in state seachId time, leading to the following two questions:
- 1.Detail are accompanied by a re-created, resulting in unnecessary waste of performance
- 2.Home components, handleSearchId methods are re-created
solution
memo+useCallback
Question 1 memo for use
/** 对Detail组件,包上一层memo,这是hooks提供的一个api */
...
let Detail = memo(() => {
console.log('Detail Component 被渲染了')
return (
<span>test</span>
)
})
export default Detail
React.memo similar React.PureComponent, can do relatively shallow for props, to prevent the repetition rendered ineffective components!
For Question 2 use useCallback
/** 改写Home.tsx */
...
let Home = () => {
const [searchId, setSearchId] = useState(0)
const handleSearchIdChange = (e) => {
console.log('handleSearchChange 被创建了')
setSearchId(e.target.value)
}
return (
<>
<Search handleSearchId={handleSearchId}/>
<Detail />
</>
)
}
export default Home
useCallback inline caching function for, when a function of preventing the formation of new properties due to updated rendering cause repeated subassembly