I think my useEffect is broken.
I have on the parent component
<div className={redactKategori}>
<select className="form-control form-control-sm mb-3 mr-2" name="betalt" defaultValue={'välj kategori'} onChange={e => { e.preventDefault(); setKate(e.target.value); setRedactKategoris('d-block') }}>
<option >valj kategori</option>
{ Kategori ?
Object.keys(Kategori).map(key => {
return (
<option key={key} value={key}>{key}</option>
)
}) :
null
}
</select>
<div className={redactKategoris}>
<EditKat aa={kate} />
</div>
and on the child component
function EditKat({ aa }) {
let defaultValues = 0
useEffect(() => {
defaultValues = 2
}, [aa])
console.log(defaultValues)
}
So, as far as I understood, everytime ${kate} would get a value on the parent component, the child component would trigger the useEffect hook. However it is not working. Am I doing something wrong?
The reason for the experienced behavior is not that useEffect isn't working. It's because of the way function components work.
If you look at your child component, if useEffect is executed and the component rerenders, defaultValues would be set to 0 again, because the code inside of the function is executed on each render cycle.
To work around that, you would need to use the useState to keep your local state consistent across renders.
This would look something like this:
function EditKat({ aa }) {
// Data stored in useState is kept across render cycles
let [defaultValues, setDefaultValues] = useState(0)
useEffect(() => {
setDefaultValues(2) // setDefaultValues will trigger a re-render
}, [aa])
console.log(defaultValues)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With