skip to Main Content

In my React page, I have a table that is using array.map. The table rendering from ".map" takes a lot of time because the array lists are long.

I have an input element which has no relation with the table (they don’t affect each other). However, when there is input change, the table renders so the hundred lines are mapped again and takes a long time for the input to be seen. It seems like a lag happens every keystroke.

Can the table not render every time onChange is called? Or any way this could be solved?
I just found out about windowing, but is there a way without this, or is this the only option?

2

Answers


  1. It seems like the input is represented by state variable (created with useState hook), and its change causes whole component to re-render (as it should).

    But, as I understand, the "slow" table component is child component and gets re-rendered (long opertaion) each time parent re-renders, due to its state changes, which are not related to our "heavy" component.

    So, there is a optimization technique to prevent that – memoization. Just use React.memo, that will help you with the slow render of a table and will limit re-renders only if the props of that component has changed.

    Before

    function App() {
        const [val, setVal] = React.useState('')
        return (
            <>
                <input value={val} onChange={e => setVal(e.target.value)}/>
                <MySlowTable />
            </>
        )
    }
    

    After

    const MySlowTableMemo = React.memo(MySlowTable)
    
    function App() {
        return (
            <>
                <input value={val} onChange={e => setVal(e.target.value)}/>
                <MySlowTableMemo />
            </>
        )
    }
    
    Login or Signup to reply.
  2. in short
    explore Hooks in react once.

    we use Hooks when we need to change something when something else is being changed

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search