Zusstand: 어리석은 간단한 상태 관리 도구!
주스탄트란?
Zusstand pmndrs의 제작자:
Zustand is a small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy api based on hooks, isn't boilerplatey or opinionated.
Check out the repo to learn more
Zusstand가 실제로 작고 빠르고 확장 가능한 베어본 상태 관리 솔루션이라는 것을 아래 예에서 알 수 있습니다.
왜 Redux/Context-API보다 Zusstand를 사용합니까?
기본 사용법
예제로 카운터 앱을 만들 것입니다.
npm i zustand
// store/store.js
import create from 'zustand'
export const useStore = create(set => ({
count: 0,
incrementCount: () => set(state => ({count: state.count + 1})),
incrementCount: () => set(state => ({count: state.count - 1}))
}))
Note
create
is a special function that creates a state object with the props we defined
set
is a special function that merges the state.The curly braces inside parenthesis
() => ({})
tells javascript that we are returning an object instead of it being a code block
import {useStore} from "./store/store.js"
function MyComponent() {
// you can destrcture the state
// const count = useStore({count} => count)
const count = useStore(state => state.count)
const incrementCount = useStore(state => state.decrementCount)
const incrementCount = useStore(state => state.decrementCount)
return
<div>
<p>Count: {count}</p>
<button onClick={() => incrementCount}>Increment</button>
<button onClick={() => incrementCount}>Decrement</button>
</div>
}
그리고 짜잔! 간단하죠?
Zusstand Todo 앱
Zusstand로 작업하는 것이 얼마나 쉬운지 보여주기 위해 ole Todo 앱을 만들 것입니다.
The purpose of this article is just to show how to use Zustand so i'll keep the app simple and not include check, rename or delete functionality for the todos
npx create-react-app zustand-example && cd zustand-example
설치가 완료되면 입력 및 제출 버튼이 있는 간단한 양식을 만들 것이므로 다음을 입력합니다.
import styles from "./App.module.css";
import {useState} from "react"
function App() {
const handleSubmit = (e) => {
e.preventDefault()
}
return (
<div className={styles.App}>
<form onSubmit={handleSubmit} className={styles.form}>
<input value={value} onChange={(e) => setValue(e.currentTarget.value)} className={styles.input} placeholder="Add a new todo" />
<button className={styles.button}>Add</button>
</form>
</div>
);
}
export default App;
보시다시피 이것은 제어된 입력이 있는 일반 양식입니다. 양식은 다음과 같습니다.
!
이것이 궁금하다면 스타일
.App {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background: whitesmoke;
}
.form {
width: 30%;
height: 80%;
background: white;
border-radius: 12px;
padding: 2rem;
display: flex;
flex-direction: column;
align-items: center;
box-shadow: 0 0 5px black;
}
.input {
width: 80%;
padding: 10px 12px;
}
.button {
color: white;
background: aqua;
padding: 10px 20px;
margin: 20px 0;
border: none;
width: 140px;
}
이제 Zusstand를 구현할 것입니다.
npm i zustand
src
폴더 안에 store
store.js
를 만듭니다.store 객체 내부에 배열인
todos
속성과 배열에 새 할 일을 푸시하는 addTodo
메서드를 생성합니다.import create from "zustand";
export const useStore = create((set) => ({
todos: [],
addTodo: (todo) =>
set((state) => ({
todos: [...state.todos, todo],
})),
}));
여기에서 거의 완료되었습니다. 이제 양식에 논리를 추가해야 합니다.
useStore
후크 및 호출import {useStore} from "./store/store"
function App() {
const todos = useStore((state) => state.todos);
const addTodo = useStore((state) => state.addTodo);
}
handleSubmit
함수에서 todos 배열에 새 할일을 제출합니다.const handleSubmit = (e) => {
e.preventDefault()
addTodo(value);
}
마지막으로
todos
배열을 매핑하여 할 일을 나타냅니다.return (
{todos.map((todo) => {
return (
<ul>
<li>{todo}</li>
</ul>
);
})}
)
그게 다야! 앱을 테스트해 봅시다.
전체 코드:
import { useState } from "react";
import styles from "./App.module.css";
import { useStore } from "./store/store";
function App() {
const todos = useStore((state) => state.todos);
const addTodo = useStore((state) => state.addTodo);
const [value, setValue] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
addTodo(value);
setValue("");
};
return (
<div className={styles.App}>
<form onSubmit={handleSubmit} className={styles.form}>
<input
value={value}
onChange={(e) => setValue(e.currentTarget.value)}
className={styles.input}
placeholder="Add a new todo"
/>
<button className={styles.button}>Add</button>
{todos.map((todo) => {
return (
<ul>
<li>{todo}</li>
</ul>
);
})}
</form>
</div>
);
}
export default App;
타이프스크립트
typescript를 사용하는 경우
interface
로 상점 유형을 정의할 수 있습니다.import create from "zustand";
interface IStore {
todos: string[];
addTodo: (todo: string) => string
}
export const useStore = create<IStore>((set) => ({
todos: [],
addTodo: (todo) =>
set((state) => ({
todos: [...state.todos, todo],
})),
}));
결론
Zusstand 사용을 권장하는 이 게시물의 끝 부분에 도달했습니다. 이 게시물이 마음에 들면 더 많은 것을 위해 나를 팔로우할 수 있습니다. 읽어주셔서 감사합니다. 행복한 상태 관리!
또한 내 다른 게시물을 확인하십시오: "useReducer vs useState"
useState 대 useReducer: 무엇이며 언제 사용해야 합니까?
m0nm · 2월 19일 · 3분 읽기
#react
#javascript
#tutorial
#webdev
프로젝트를 빌드하는 방법에 대한 몇 가지 팁
프로젝트 구축 방법에 대한 초보자 가이드
m0nm · 2월 22일 · 5분 읽기
#beginners
#tutorial
#programming
#codenewbie
Reference
이 문제에 관하여(Zusstand: 어리석은 간단한 상태 관리 도구!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/m0nm/zustand-stupid-simple-state-management-tool-3mh9텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)