J
J
JavaSscriptNoob2022-02-16 18:29:40
React
JavaSscriptNoob, 2022-02-16 18:29:40

How to decompose logic to avoid unnecessary parent component renders due to useState?

Hello everyone, I have a component BasicFormthat will render different types of forms depending on the prop type , for example: a login form, a form for creating something, etc. This component must be props inputColumns which is the fields that we will render in child computers. our form, now it is written in the form component itself, but I would like it to come through props, its appearance is something like this:

const inputColumns = [
    {
      value: title,
      handleInputChange: setTitle,
      fieldName: "title",
    ...
    },
    {
      value: description,
      handleInputChange: setDescription,
      fieldName: "description",
     ...
    },
  ];

The whole problem is that my idea of ​​how to add a field function to this array of objects handleInputChangeseems to me, to put it mildly, not very good. (at the moment I want to pass this array without a field handleInputChange and add functions there through the map of this array of objects, having previously written all the functions that I want to add there to the callbacks array or something like that in the code, it would look something like this:
const callbacks=[fn1,fn2] ; inputColumns.map((item,i)=>{...item,handleInputChange: callbacks[i]})
, such an idea seems to me, to put it mildly, not very.
) . Yes, I could transfer the function there right away, but I want to use setState in child components , and already put the state change function as a function. Can anyone come up with a bright idea? Thank you ! Here is the component codeBasicForm
{
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");  // все useState хочу поместить в дочерние комп. что бы избежать лишних ре-рендеров

  const inputColumns = [ // этот массив должен приходить в пропсах
    {
      value: title,
      handleInputChange: setTitle,
      type: "text",
      className: "form-control",
      id: "floatingInput",
      placeholder: "[email protected]",
      label: "Enter title",
      fieldName: "title",
    },
    {
      value: description,
      handleInputChange: setDescription,
      type: "text",
      className: "form-control",
      id: "floatingInput",
      placeholder: "your first name",
      label: "Enter description ",
      fieldName: "description",
    },
  ];

  const data = inputColumns.reduce( // собираю данные для отправки на сервер
    (acc, field) => {
      return acc.hasOwnProperty(field.fieldName)
        ? { ...acc }
        : { ...acc, [field.fieldName]: field.value };
    },
    { userId }
  );

  const handleButtonClick = () => {
    buttonClickAction(data);
  };
  const renderBasicForm = (type) => { // функция которая ренедрит форму в зависимости от type
    switch (type) {
      case CREATE_FORM:
        return (
          <CreateItemForm // в этой форме будут все useState с состояниями , внутри этой комп. я хотел бы прсваивать функц. useStat'a в inputColumns
            handleButtonClick={handleButtonClick}
            inputColumns={inputColumns}
          />
        );
      default:
        <div>There is no data to display</div>;
    }
  };
  return <Box>{renderBasicForm(type)}</Box>;
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question