0
votes

I'm having a problem with my application. We have an application which has multiple form input components (radio buttons, text inputs etc). We noticed that our forms are re-rendering multiple times when user interacting with these elements. We tried to use useMemo and useCallback hooks which it works very well with useReducers, but it has a problem when we are trying to use in setState. It resetting the previous state values when user trying to enter values

const {useState, useCallback} = React;

const CustomInputBox = React.memo(({label, id, value, onChange}) => {
  console.log(`${label} rendered`);
  return (
    <div className="custom-wrapper">
      <label>{label}</label>
      <input
        type="text"
        value={value}
        onChange={event => onChange(id, event.target.value)}
       
        />
    </div>
  )
})

const CustomSelect = React.memo(({label, id, value, onChange}) => {
  console.log(`${label} select rendered`);
  return (
    <div className="custom-wrapper">
      <label>{label}</label>
      <select name="cars" onChange={event => onChange(id, event.target.value)}>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>

    </div>
  )
})

const FormApp = ({}) => {
   const [state, setState] = useState({
    name : '',
    age: '',
    car: ''
  });
  
  const updateForm = useCallback( (field, value) => {
    setState({...state, 
              [field]: value
             })
  }, [])
  
  return (
    <div>
      <CustomInputBox 
        label="Name" 
        id="name"
        key="name"
        value={state.name} 
        onChange={updateForm}
        />
      <CustomInputBox 
        label="Age" 
        id="age"
        key="age"
        value={state.age} 
        onChange={updateForm}
        />
        <CustomSelect 
          label="Car type" 
          id="car"
          value={state.car} 
          onChange={updateForm}
          />
    </div>
  );
}


ReactDOM.render(
  <div className="App">
        <main>          
          <FormApp />
        </main>
      </div>,
  document.getElementById('root')
);
1

1 Answers

0
votes

You can actually remove the useCallback on the updateForm function. Try

const updateForm = (field, value) => setState({ ...state, [field]: value });