简体   繁体   中英

React re-renders unnecessary components

I'm new to React, so please explain why this is happens(I guess because I'm re-creating the array of objects, but I'm not sure and don't know how to fix this) and how to fix this this.

I think it's better to show the code, rather than talk about it, so:

App.js

import { useState } from "react";
import Input from "./Input";

let lastId = 2;

function App() {
  const [inputsValues, setInputsValues] = useState([
    { id: 1, value: "" },
    { id: 2, value: "" },
  ]);

  const handleChange = (e, id) => {
    setInputsValues((prevState) => {
      const newState = [...prevState];
      const index = newState.findIndex((input) => input.id === id);
      newState[index].value = e.target.value;
      return newState;
    });
  };

  const addNewInput = () => {
    setInputsValues((prevState) => {
      const newState = [...prevState];
      newState.push({ id: ++lastId, value: "" });
      return newState;
    });
  };

  return (
    <div className="App">
      <div>
        <button onClick={addNewInput}>Add new input...</button>
      </div>

      {inputsValues.map((input) => (
        <div className="input-wrap">
          <Input
            key={input.id}
            id={input.id}
            value={input.value}
            handleChange={handleChange}
          />
        </div>
      ))}
    </div>
  );
}

export default App;

Input.js

import { useRef } from "react";

const Input = ({ id, value, handleChange }) => {
  const renderAmount = useRef(0);

  return (
    <>
      <div> Rendered: {renderAmount.current++}</div>
      <input
        id={id}
        type="text"
        value={value}
        onChange={(e) => handleChange(e, id)}
      />
    </>
  );
};

export default Input;

Thanks

Seems like you just have to wrap your Input component in memo so that it only rerenders if its props change. So i imported the memo function in the top and called it on the right side of the assignment, so that it 'wraps' your component and makes it memoized.

 import { useRef, memo } from "react"; const Input = memo(({ id, value, handleChange }) => { const renderAmount = useRef(0); return ( <> <div> Rendered: {renderAmount.current++}</div> <input id={id} type="text" value={value} onChange={(e) => handleChange(e, id)} /> </> ); }); export default Input;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM