Strange usage of ref
This is a confusing piece of code that looks confusing at first glance:
function App() { const [dom, setDOM] = useState(null); return <div ref={setDOM}></div>; }
Let's analyze its role.
first,ref
There are two forms (there were 3):
- Like
{current: T}
Data structure - The callback function form will be in
ref
Triggered when updated or destroyed
In the examplesetDOM
yesuseState
ofdispatch
There are two types of calling methods:
- Directly pass the updated value, for example
setDOM(xxx)
- Methods to pass update status, such as
setDOM(oldDOM => return /* some processing logic */)
In the example, although abnormal,ref
The second form anddispatch
The second form is indeed in line.
That is, in the example, passed toref
ofsetDOM
Method, will bediv corresponds to DOMExecute when updated or destroyed, thendom
What is saved in the state isdiv corresponds to DOMlatest value.
This has been achieved to a certain extentPerceive real-time changes in DOMThis is simply usedref
Ability that cannot be possessed.
Strange usage of useMemo
Usually we thinkuseMemo
Used to cache variablesprops
,useCallback
Used to cache functionsprops
。
But in actual projects, if you want to passCache propsThe method to achieve the purpose of optimization of subcomponent performance requires ensuring:
- All passed to subcomponents
props
The references to theuseMemo
) - Subcomponent usage
Similar to this:
function App({todos, tab}) { const visibleTodos = useMemo( () => filterTodos(todos, tab), [todos, tab]); return <Todo data={visibleTodos}/>; } // To achieve the purpose of Todo performance optimizationconst Todo = (({data}) => { // ...Omit logic})
now thatuseMemo
Variables can be cached, why not directly cache the return value of the component? Similar to this:
function App({todos, tab}) { const visibleTodos = useMemo( () => filterTodos(todos, tab), [todos, tab]); return useMemo(() => <Todo data={visibleTodos}/>, [visibleTodos]) } function Todo({data}) { return <p>{data}</p>; }
In this way, subcomponents that require performance optimization no longer need to be manually wrapped, only when
useMemo
The subcomponents will be re-established after dependency changesrender
。
Summarize
In addition to these two strange ways of writing, what other strange things do you encounterReact
What about writing?