Home >Web Front-end >JS Tutorial >Why Should We Avoid `object` Props in React
In React, transmitting objects to the PROPS will trigger re -rendering (you need to use
useMemo
If possible, the original value should be passed to PROPS. React uses "shallow comparison" to detect any changes in props and status. Specifically, it uses JavaScript syntax to compare. So, what is the result of the following code?
Object.is()
The answer is ...
<code class="language-javascript">Object.is( { hello: "world" }, { hello: "world" }, );</code>
Although the two objects look the same, the JavaScript object is passed according to reference, which means that even if they look the same, they are not the same object: they have different distribution in memory. false
, it will still re -renders:
memo
We can avoid unnecessary re -rendering by using the right React Hook
<code class="language-javascript">const Parent = () => { const user = { name: "Lee", age: 30 }; return <Child user={user} />; }; // Child 组件重新渲染 const Child = React.memo(({ user }: { user: { name: string; age: number } }) => { console.log("Child 渲染"); return <div>{user.name}</div>; });</code>
useMemo
But, and
<code class="language-javascript">const Parent = () => { const user = React.useMemo(() => ({ name: "Lee", age: 30 }), []); return <Child user={user} />; };</code>
Pass the original value to PROPS useMemo
useCallback
In this example, it is not effortless to pass each key to the props of the child component. However, sometimes we need to process large objects with more than 10 key values.
Create other components (the principle of single responsibility)
<code class="language-javascript">const Parent = () => { const user = { name: "Lee", age: 30 }; return <Child age={user.age} name={user.name} />; };</code>
If we follow the Solid principle, we can consider creating multiple smaller components to process each prop. Or, at least the key value of the object is assigned to multiple components.
The above is the detailed content of Why Should We Avoid `object` Props in React. For more information, please follow other related articles on the PHP Chinese website!