React - Using useMemo() still causes keyboard input to slow down
P粉340264283
P粉340264283 2023-09-03 17:16:59
0
1
576
<p>I have this code, which has many input boxes, each input box is used to modify a price value. Since there are a lot of input boxes (3 prices per area and 3 pricing per price), to avoid re-rendering everything every time, I used useMemo on the function that updates the input box value, and in addition to In addition, I also used useReducer to avoid the code being too long to control the input box. </p> <p>However, entering characters (or numbers) is not displayed instantly, but takes a short period of time to be displayed, let alone continuous input. </p> <pre class="brush:php;toolbar:false;">const handleUpdate = useMemo( () => (property, valu, obid) => { dispatch({ type: "UPDATE_DATA", property, payload: valu, id: obid }); }, [dispatch] );</pre> <p>And there is also a reducer:</p> <pre class="brush:php;toolbar:false;">function reducer(state, action) { switch (action.type) { ... case "UPDATE_DATA": return { ...state, data: state.data.map((item) => { if (item.id === action.id) { return { ...item, [action.property]: action.payload }; } return item; }), }; } }</pre> <p>I recommend checking the entire code, as the problem (or solution) may lie elsewhere. In order to view the entire code you can refer to this sandcodebox link. Please forgive me for copying part of the code, which resulted in poor css format. Note that the fetch function has been replaced by a long array of simulated data. </p> <p>Link: https://codesandbox.io/s/unruffled-feynman-g9nox2?file=/src/App.js</p>
P粉340264283
P粉340264283

reply all(1)
P粉420868294

Typically, useMemo is used to cache expensively calculated values ​​during rendering. In your case, however, you don't have any expensive rendering calculations; you just render a very large tree every time the input changes. In fact, because all state is on the App component, the entire app is re-rendered every time.

The way to optimize this problem in React is to skip rendering components as much as possible. To do this, split unrelated parts of the page into different components. Once the logic is separated, wrap it with React.memo(), which is a different optimization technique that can skip component rendering entirely.

To me, the most obvious changes you can make are:

  1. Move TodosDatos out of the App component as it is a constant and does not need to be redefined on every render (which may take up memory).
  2. Put your <Table> into a new component and use React.memo() to memoize it. Make sure to pass all table dependency values ​​to the new component's props.

I implemented these changes here: https://codesandbox.io/s/green-breeze-mmum6n?file=/src/App.js. You should now notice that typing is almost instantaneous. You can also do multiple optimizations elsewhere to get better performance.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template