Although React
the official website uses a lot of space to introduce best practices, due to JSX
the flexibility of the grammar, strange React
writing methods always appear.
This article introduces two strange (but meaningful in some scenarios) React
writing methods. You are also welcome to discuss the strange writing methods you have encountered in the comment area.
Welcome to join the human high-quality front-end exchange group and lead flying
Weird usage of ref
This is a piece of code that is confusing at first glance:
function App () { const [dom, setDOM] = useState ( null ); return < div ref = {setDOM} > </ div > ; }
Let’s analyze its function.
First, ref
there are two forms (there used to be 3):
{current: T}
data structure- Callback function form, which will
ref
be triggered when updating or destroying
The setDOM
method in the example also has two calling forms:useState
dispatch
- Pass the updated value directly, such as
setDOM(xxx)
- Pass a method to update the status, such as
setDOM(oldDOM => return /* 一些处理逻辑 */)
In the example, although anomalous, ref
the second form of and dispatch
the second form of do indeed fit.
In other words, the method passed in the example will ref
be executed when the DOM corresponding to the div is updated and destroyed, so what is saved in the state is the latest value of the DOM corresponding to the div .setDOM
dom
This enables the perception of real-time changes in the DOMref
to a certain extent, which is an ability that cannot be achieved simply by using it .
Weird usage of useMemo
Usually we think of useMemo
it as caching variables props
and useCallback
functions props
.
But in actual projects, if you want to optimize the performance of subcomponents by caching props , you need to ensure at the same time:
- All references passed to child components
props
are unchanged (such as throughuseMemo
) - Subcomponent usage
React.memo
Something like this:
function App ( {todos, tab} ) { const visibleTodos = useMemo ( () => filterTodos (todos, tab), [todos, tab]); return < Todo data = {visibleTodos}/ > ; } // In order to achieve the purpose of Todo performance optimization const Todo = React . memo ( ( {data} ) => { // ...omit logic })
Since useMemo
variables can be cached, why not directly cache the return value of the component? Something like 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 wrapped manually React.memo
, and useMemo
the subcomponents will only be repackaged when dependencies change render
.
Summarize
In addition to these two strange ways of writing, what other strange React
ways of writing have you encountered?