Skip to content

Instantly share code, notes, and snippets.

@joonseokhu
Created January 11, 2020 11:46
Show Gist options
  • Save joonseokhu/679884bcf4708ca0ec650b46784b6d79 to your computer and use it in GitHub Desktop.
Save joonseokhu/679884bcf4708ca0ec650b46784b6d79 to your computer and use it in GitHub Desktop.
useEffect trouble
import React, { useState, useReducer, useEffect } from 'react';
const Inner = props => {
const {
value: passedValue,
onChange,
} = props;
const [value, setValue] = useState(passedValue);
const handleChange = nextValue => {
setValue(nextValue);
};
useEffect(() => {
if (onChange) onChange(value);
console.log('inner component effect');
}, [value]); // React Hook useEffect has a missing dependency: 'onChange'. Either include it or remove the dependency array
return (
<>
<input type="text" value={value} onChange={e => handleChange(e.target.value)} />
</>
);
};
const reducer = (prev, next) => ({
...prev,
...next,
});
const Outer = props => {
const [values, setValues] = useReducer(reducer, {
a: '',
b: '',
c: '',
d: '',
e: '',
});
const handleChange = key => value => {
setValues({
[key]: value,
});
};
return (
<>
<Inner value={values.a} onChange={handleChange('a')} />
<Inner value={values.b} onChange={handleChange('b')} />
<Inner value={values.c} onChange={handleChange('c')} />
<Inner value={values.d} onChange={handleChange('d')} />
</>
);
};
export default Outer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment