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를 사용합니까?


  • 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"







    프로젝트를 빌드하는 방법에 대한 몇 가지 팁




    좋은 웹페이지 즐겨찾기