I have a problem that I've been trying to solve for the past couple of days:
I'm using a Context Provider for form fields and for whatever reason fields keep overwriting each other when I use memo.
Provider:
export const Context = React.createContext();
function Form_Provider({ values, onChange, children }) {
return (
<Context.Provider value={{ values, onChange }}>
{children}
</Context.Provider>
)
});
export default Form_Provider
Field:
function Field({ label, name }) {
const { values, onChange } = useContext(Context);
return (
<Memorable
label={label}
onChange={({ target: t }) => onChange({ name, value: t.value })}
value={values[name]}
/>
);
}
const Memorable = React.memo(props => {
return (
<Form.Item label={props.label}>
<Input
value={props.value}
onChange={props.onChange}
/>
</Form.Item>
</>
)
}, ({ value: newValue}, { value: oldValue }) => newValue == oldValue)
Form
const [formValues, setFormValues] = useState({ field1: 'Foo', field2: 'Bar' });
<Form.Provider
values={formValues}
onChange={({ name, value }) => setFormValues({...formValues, [name]: value }))
>
<Form.Field name='field1' label="Field 1" />
<Form.Field name='field2' label="Field 2" />
</Form.Provider>
(Tried to simplify it as much as possible)
In my actual code I've added a json print prettifier to track the state for every field and it works out until every single field when i only edit one field. However, once I start editing another field the first field I've edited goes back to its original state and/or some other weird in between state from it's past.
If I dont use Memo it works but that can't be the solution as I'll be working with a lot of fields and that would cause a lot of re-rendering.
Anyone any idea what's going on here?
Addition:
I've already tried using an internal reducer for this and passing down a dispatch function. As long as I don't try to manage the state outside of the provider everything works.