了解 React Native 如何渲染元件對於建立高效且高效能的應用程式至關重要。當元件的狀態或屬性變更時,React 會自動更新使用者介面(UI)以反映這些變更。結果,React 再次呼叫元件的 render 方法來產生更新的 UI 表示。
在本文中,我們將探討三個 React Hook 以及它們如何防止 React 中不必要的渲染
這些工具使我們能夠透過避免不必要的重新渲染、提高效能和有效儲存值來最佳化程式碼。
在本文結束時,我們將更了解如何使用這些方便的 React hook 讓我們的 React 應用程式更快、更快回應。
在 React 中,useMemo 可以防止不必要的重新渲染並最佳化效能。
讓我們來探索一下 useMemo 鉤子如何防止 React 元件中不必要的重新渲染。
透過記住函數的結果並追蹤其依賴關係,useMemo 確保僅在必要時重新計算該過程。
考慮以下範例:
import { useMemo, useState } from 'react'; function Page() { const [count, setCount] = useState(0); const [items] = useState(generateItems(300)); const selectedItem = useMemo(() => items.find((item) => item.id === count), [ count, items, ]); function generateItems(count) { const items = []; for (let i = 0; i < count; i++) { items.push({ id: i, isSelected: i === count - 1, }); } return items; } return ( <div className="tutorial"> <h1>Count: {count}</h1> <h1>Selected Item: {selectedItem?.id}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Page;
上面的程式碼是一個名為Page的React元件,它使用useMemo來最佳化selectedItem計算。
解釋如下:
使用 useMemo 透過記住 items.find 操作的結果來最佳化效能。它確保僅在依賴項(計數或項目)變更時才執行 selectedItem 的計算,從而防止後續渲染時不必要的重新計算。
應有選擇地對計算密集型操作採用記憶化,因為它會為渲染過程帶來額外的開銷。
React 中的 useCallback 鉤子允許記憶函數,防止它們在每個元件渲染期間被重新建立。透過利用 useCallback。只要其依賴項保持不變,部件僅建立一次並在後續渲染中重複使用。
考慮以下範例:
import React, { useState, useCallback, memo } from 'react'; const allColors = ['red', 'green', 'blue', 'yellow', 'orange']; const shuffle = (array) => { const shuffledArray = [...array]; for (let i = shuffledArray.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]]; } return shuffledArray; }; const Filter = memo(({ onChange }) => { console.log('Filter rendered!'); return ( <input type='text' placeholder='Filter colors...' onChange={(e) => onChange(e.target.value)} /> ); }); function Page() { const [colors, setColors] = useState(allColors); console.log(colors[0]) const handleFilter = useCallback((text) => { const filteredColors = allColors.filter((color) => color.includes(text.toLowerCase()) ); setColors(filteredColors); }, [colors]); return ( <div className='tutorial'> <div className='align-center mb-2 flex'> <button onClick={() => setColors(shuffle(allColors))}> Shuffle </button> <Filter onChange={handleFilter} /> </div> <ul> {colors.map((color) => ( <li key={color}>{color}</li> ))} </ul> </div> ); } export default Page;
上面的程式碼示範了 React 元件中的簡單顏色過濾和洗牌功能。讓我們一步一步來:
useCallback 鉤子用於記憶handleFilter 函數,這表示函數只建立一次,並且如果相依性(在本例中為顏色狀態)保持不變,則在後續渲染中重複使用。
This optimization prevents unnecessary re-renders of child components that receive the handleFilter function as a prop, such as the Filter component.
It ensures that the Filter component is not re-rendered if the colors state hasn't changed, improving performance.
Another approach to enhance performance in React applications and avoid unnecessary re-renders is using the useRef hook. Using useRef, we can store a mutable value that persists across renders, effectively preventing unnecessary re-renders.
This technique allows us to maintain a reference to a value without triggering component updates when that value changes. By leveraging the mutability of the reference, we can optimize performance in specific scenarios.
Consider the following example:
import React, { useRef, useState } from 'react'; function App() { const [name, setName] = useState(''); const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <div> <input type="text" value={name} onChange={(e) => setName(e.target.value)} ref={inputRef} /> <button onClick={handleClick}>Focus</button> </div> ); }
The example above has a simple input field and a button. The useRef hook creates a ref called inputRef. As soon as the button is clicked, the handleClick function is called, which focuses on the input element by accessing the current property of the inputRef ref object. As such, it prevents unnecessary rerendering of the component when the input value changes.
To ensure optimal use of useRef, reserve it solely for mutable values that do not impact the component's rendering. If a mutable value influences the component's rendering, it should be stored within its state instead.
Throughout this tutorial, we explored the concept of React re-rendering and its potential impact on the performance of our applications. We delved into the optimization techniques that can help mitigate unnecessary re-renders. React offers a variety of hooks that enable us to enhance the performance of our applications. We can effectively store values and functions between renders by leveraging these hooks, significantly boosting React application performance.
以上是如何防止不必要的 React 元件重新渲染的詳細內容。更多資訊請關注PHP中文網其他相關文章!