skip to Main Content

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


  1. 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]
    );
    
    Login or Signup to reply.
  2. 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]
        );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search