---
# System prepended metadata

title: Storing State
tags: [Stores]

---

# Storing State

> * 如有錯誤處指正或任何建議，懇請留言，感謝!
> * 搭配 ChatGPT 進行翻譯，請小心服用
> * ▸ ... 為英文原文

:::spoiler ...
Applications need to store state to be useful, otherwise they're just static pages.

Qwik tracks application state for two reasons:

To serialize data when the application pauses on the server, and deserialize as the application resumes on the client.

To create subscriptions on stores so that Qwik knows which components to re-render. If Qwik didn't track subscriptions, it would have to re-render the whole application - which would defeat the purpose of lazy-loading.

The component on the right doesn't work yet because counter is just a plain object with no subscriptions. As a result, Qwik doesn't know when counter.count changes, and therefore doesn't know to re-render the `<App>` component.

Your task: Wrap counter in useStore() to enable dependency tracking and automatic re-rendering.

Serialization
Open the HTML tab to see what information is serialized by the server. Look in the `<script type="qwik/json">` block for serialization information and notice that:

{count: 0} is in the serialized state.
At the end of the serialized state are subs which contain "count". These subscriptions tell Qwik which component to re-render as the state changes.
Qwik state is in no way tied to the component that created it. The state can be passed to any component in the application and Qwik creates the needed subscriptions and re-renders only the affected components.
:::



應用程式要有用就需要存取state，要不然這就只是個靜態網頁。

Qwik之所以追蹤應用程式的state有兩個理由：

1. 應用程式在server暫停時serialize data而應用程式恢復後在客戶端deserialize

2. 讓Stores可以被訂閱這樣Qwik就能知道哪一個component需要重新渲染。如果沒有這些訂閱Qwik就得渲染整個程式，延遲加載就沒有意義了。

Component:
```javascript=
import { component$ } from '@builder.io/qwik';

export default component$(() => {
  const counter = { count: 0 };

  return (
    <>
      <div>Count: {counter.count}</div>
      <button onClick$={() => counter.count++}>+1</button>
    </>
  );
});
```

上面這個component還不能運作因為`counter`還只是一個沒有訂閱的普通object，Qwik還不知道`counter.count`有更新所以也不知道什麼時候要重新渲染這個component。

**任務**： 用useStore()來包`counter`使Qwik能自動重新渲染。


###### tags: `Stores`


