score:1

Accepted answer

there are 2 things wrong with your code:

  1. action.payload.value does not exist, it is action.payload.e.value
  2. you cannot use the event in the reducer or you'll get an error that synthetic event will be reused, use the event value in the action instead
  3. an action creator should only create an object, dispatch it in the component.

const update_field = 'update_field';
const reducer = (state, { type, payload }) => {
  if (type === update_field) {
    const { input, value } = payload;
    return { ...state, [input]: value };
  }
};
const handlechangefor = (input, e) => {
  //event will be re used and cause an error
  //  use value instead of passing event to
  //  reducer
  return {
    type: update_field,
    payload: { input, value: e.target.value },
  };
};
const pureinput = react.memo(function pureinput({
  value,
  onchange,
}) {
  const r = react.useref(0);
  r.current++;
  return (
    <label>
      pure input rendered: {r.current} times
      <input
        type="text"
        onchange={onchange('pure')}
        value={value}
      />
    </label>
  );
});
const app = () => {
  const [state, dispatch] = react.usereducer(reducer, {
    name: '',
    pure: '',
  });
  //if you want to optimize you can use usecallback
  const handlechange = react.usecallback(
    (input) => (e) => dispatch(handlechangefor(input, e)),
    []
  );

  return (
    <div>
      <div>
        <input
          type="text"
          onchange={(e) =>
            dispatch(handlechangefor('name', e))
          }
          value={state['name']}
        />
      </div>
      <pureinput
        value={state['pure']}
        onchange={handlechange}
      />
    </div>
  );
};
reactdom.render(<app />, document.getelementbyid('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>


Related Query

More Query from same tag