I'm using useEffect
which should update my component whenever the value selected
of my state updates:
const Thumbnail = ({ image }) => {
const [state, dispatch] = useContext(Context);
const [checked, setChecked] = useState(getChecked());
useEffect(() => {
setChecked(getChecked())
}, [state.selected])
...
}
export default Thumbnail
But the Function is called everytime anything in my state is updated. For example when an other component updates state.all
, the useEffect()
method is being called.
How can I avoit this and only call the useEffect()
method when state.selected
is being changed?
I think what you need is useMemo.
useMemo
will only recompute the memoized value when one of the dependencies has changed.
const checked = useMemo(() => getChecked(), [state.selected]);