Home > front end >  Dialog form constantly reendering elements slowing down my application (and crashing)
Dialog form constantly reendering elements slowing down my application (and crashing)

Time:03-23

I tried to recreate this here: https://codesandbox.io/s/romantic-galois-msld0l?file=/src/App.js

Using a basic todo list. Click on edit todo button and a form modal should appear. Everytime you edit the form, it rerenders. In my main application it slows down the code and crashes it because it has 100 rows. I'm stuck on how to fix this. I'm also beginnerish to react and wondering why this happens?

i added a console.log for every re-render, so to demonstrate this further: https://gyazo.com/cfcdb99c1bd0a60aaf5259ece44721bb

edit: fixed using suggestions below: https://codesandbox.io/s/strange-browser-ymxfhp?file=/src/App.js

CodePudding user response:

Your input is changing the state on every input stroke.

In these kind of situation, you should create a new component e.g. SingleTextInput, and let the onChange event be isolated within the component itself.

SingleTextInput can then trigger new state in Parent component when you click Save.

E.g.

const SingleInput = ({ id, onSave, task, name }) => {
    const [ input, setInput ] = useState({ id, name, task })

    const onSaveButtonClicked = () => {
        onSave({ id, task: input.task, name: input.name })

    } 
    return ( //some text input )
}

then in your parent you use something like

<SingleInput id={id} onSave={someFunctionThatSaveState} task={task} name={name} />

The benefit of this is when you use onChange in input, it doesn't trigger re-rendering in the parent component e.g. App component.

CodePudding user response:

It is crashing your application because it is trying to render so much data when you try to edit as you said it has 100 rows and I think that is the main reason for crashing your application.

You should create pagination in your app so that it only renders a specific amount of rows which will reduce the load on your app and it won't crash anymore.

  • Related