I am trying to set a const value using useState hook:
const [liked, setLiked] = useState(messages?.likes?.some((like)=>like.id === user.id))
Here, when messages
change, liked
value doesn’t update. I know I can use useEffect
hook, but is there a way to define the liked
value without using useEffect
hook?
EDIT: I need to use setState value, too, besides auto updated value.
2
Answers
Yes, use the
useMemo
hook.useMemo
is basicallyuseState
+useEffect
to keep it "synchronized". This is what is generally called derived state, and as such it is considered a bit of a React anti-pattern to store derived state in actual React state.Example:
If you want the value to update only when messages change, you can use useMemo to memoize the value. This will ensure that the liked value is recalculated only when messages are updated.