The title is a little “click bait”, but the idea is not wrong.
I don’t have the opinion that useEffect is a bad hook, actually it is quite the opposite. But in React, which works as a .
But wait, and if I have the case where I need to sync a state?
Yes, it’s very rare cases and perhaps there are better solution options, but imagine we have a post in a app and we want to have a local state to handle optimistic updates, when the user clicks on like button, but that it syncs with external state (coming from backend) to really know if the like happened.
Mutable derivations
This is a case where we need a primitive where we can do state and derivation at the same time. Conceptually speaking, we can think of it as a mutable derivation. . Because the only way for it to work without the effect, would be to sync the refs during the render of the component, not safe at all.
So, to keep it simple and safe, a example of hook would be like that:
const useMemoState = (memoFn, depsList) => {
const [state, setState] = useState(() => memoFn());
useEffect(() => {
setState(memoFn());
}, depsList)
return [state, setState];
}
SOCIAL SHARE CARD GENERATOR