SoFunction
Updated on 2025-04-11

2 strange react writing methods

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,refThere are two forms (there were 3):

  • Like{current: T}Data structure
  • The callback function form will be inrefTriggered when updated or destroyed

In the examplesetDOMyesuseStateofdispatchThere are two types of calling methods:

  • Directly pass the updated value, for examplesetDOM(xxx)
  • Methods to pass update status, such assetDOM(oldDOM => return /* some processing logic */)

In the example, although abnormal,refThe second form anddispatchThe second form is indeed in line.

That is, in the example, passed torefofsetDOMMethod, will bediv corresponds to DOMExecute when updated or destroyed, thendomWhat 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 usedrefAbility that cannot be possessed.

Strange usage of useMemo

Usually we thinkuseMemoUsed to cache variablespropsuseCallbackUsed 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 subcomponentspropsThe references to theuseMemo
  • Subcomponent usage

Similar to this:

function App({todos, tab}) {
    const visibleTodos = useMemo(
      () =&gt; filterTodos(todos, tab),
    [todos, tab]);
    
    return &lt;Todo data={visibleTodos}/&gt;;
}

// To achieve the purpose of Todo performance optimizationconst Todo = (({data}) =&gt; {
  // ...Omit logic})

now thatuseMemoVariables 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 whenuseMemoThe subcomponents will be re-established after dependency changesrender

Summarize

In addition to these two strange ways of writing, what other strange things do you encounterReactWhat about writing?