본문으로 건너뛰기

빠른 시작

TanStack preact-store를 시작하기 위한 기본 Preact 앱 예시입니다.

import { render } from "preact";
import { createStore, useSelector } from "@tanstack/preact-store";

// You can instantiate the store outside of Preact components too!
export const store = createStore({
dogs: 0,
cats: 0,
});

// This will only re-render when `state[animal]` changes. If an unrelated store property changes, it won't re-render

const Display = ({ animal }) => {
const count = useSelector(store, (state) => state[animal]);
return <div>{`${animal}: ${count}`}</div>;
};

const updateState = (animal) => {
store.setState((state) => {
return {
...state,
[animal]: state[animal] + 1,
};
});
};
const Increment = ({ animal }) => (
<button onClick={() => updateState(animal)}>My Friend Likes {animal}</button>
);

function App() {
return (
<div>
<h1>How many of your friends like cats or dogs?</h1>
<p>
Press one of the buttons to add a counter of how many of your friends
like cats or dogs
</p>
<Increment animal="dogs" />
<Display animal="dogs" />
<Increment animal="cats" />
<Display animal="cats" />
</div>
);
}

render(<App />, document.getElementById("root"));

useStore는 지원 중단 예정인 useSelector의 별칭으로 계속 사용할 수 있습니다.