title: keeping a local variable in react
body: <p>I want to add a pagination to my app for this reason i coded below code but there is a problem.</p>
  <p>Here is my useEffect:</p>
  <pre><code> useEffect(() =&gt; {
      let x = null;
      const unsubscribe = chatsRef
        .orderBy(&quot;createdAt&quot;, &quot;desc&quot;)
        .limit(10)
        .onSnapshot((querySnapshot) =&gt; {
          const messagesFirestore = querySnapshot
            .docChanges()
            .filter(({ type }) =&gt; type === &quot;added&quot;)
            .map(({ doc }) =&gt; {
              const message = doc.data();
  
              x = message;
  
              return { ...message, createdAt: message.createdAt.toDate() };
            });
  
          appendMessages(messagesFirestore);
  
          if (latestMessage != null) {
            if (
              new Date(
                latestMessage[&quot;createdAt&quot;][&quot;seconds&quot;] * 1000 +
                  latestMessage[&quot;createdAt&quot;][&quot;nanoseconds&quot;] / 1000000
              ) &gt;
              new Date(
                x[&quot;createdAt&quot;][&quot;seconds&quot;] * 1000 +
                  x[&quot;createdAt&quot;][&quot;nanoseconds&quot;] / 1000000
              )
            ) {
              latestMessage = x;
            }
          } else {
            latestMessage = x;
          }
        });
  
      return () =&gt; unsubscribe();
    }, []);
  </code></pre>
  <p>I got the data from my database and i saved the oldest data in to <code>latestMessage</code> (for pagination) but the problem is that:</p>
  <p>I declared my <code>latestMessage</code> out of my function like that:</p>
  <pre><code>let latestMessage = null;
  export default function ChatTutor({ route }) {
  ...
  }
  </code></pre>
  <p>And I passed my props to ChatTutor component (chatRoomId, username...) and according to that id, the room and its data are rendered. But the <code>latestMessage</code> always set some value and when i go to parent component and clicked another chatRoom, ChatTutor has a value of <code>latestMessage</code>'s other value(oldest value). How can i set <code>latestMessage</code> null when i go to the parent ?</p>