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.
3
Is there a way to set const value which can change due to its
dependencies?
Yes, use the useMemo
hook. useMemo
is basically useState
+ 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:
const isLiked = useMemo(
() => !!messages?.likes?.some((like) => like.id === user.id),
[messages, user]
);
I need to use setState value, too, besides auto updated value.
Based on the information provided if you need the local component state and are enqueueing state updates then you’ll need to also use the useEffect
hook if the goal is to keep the isLiked
state synchronized to an external source, i.e. when messages.likes
updates.
4
Here, when
messages
change,liked
value doesn’t update.
If the message changed, you should mount a new “Message” component (or how ever you call it).
If you give it a unique key
(perhaps the message
id) it should re-mount and the state would be re-calculated for that component.
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.
const liked = useMemo(
() => messages?.likes?.some((like) => like.id === user.id),
[messages]
);