Search code examples
reactjszustand

Standard way for importing Zustand properties in React


Is there an easier way to import Zustand properties and assign them in a react component?

Ex: This is the logic in ComponentA.tsx

const { propA, propB, propC,...,propZ } = useStore(state => (
  propA: state.propA,
  propB: state.propB,
  .
  .
  propZ: state.propZ
), shallow);

Instead of multiple local variables like propA and propB. What is the standard way to import?


Solution

  • Fetching everything

    The simplest way, but you will import all the data (I don't know is it will affect the performance or not)

    const App = () => {
        const state = useStore()
        return {
          <>
            <h1>{state.title}</h1>
            <p>{state.paragraph}</p>
          </>
      }
    }
    

    Selecting multiple state slices

    const title = useStore((state) => state.title)
    const paragraph = useStore((state) => state.paragraph)
    

    It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.

    const nuts = useStore((state) => state.nuts)
    const honey = useStore((state) => state.honey)
    

    If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can tell zustand that you want the object to be diffed shallowly by passing the shallow equality function.

    import shallow from 'zustand/shallow'
    
    // Object pick, re-renders the component when either state.nuts or state.honey change
    const { nuts, honey } = useStore(
      (state) => ({ nuts: state.nuts, honey: state.honey }),
      shallow
    )
    
    // Array pick, re-renders the component when either state.nuts or state.honey change
    const [nuts, honey] = useStore((state) => [state.nuts, state.honey], shallow)
    
    // Mapped picks, re-renders the component when state.treats changes in order, count or keys
    const treats = useStore((state) => Object.keys(state.treats), shallow)
    For more control over re-rendering, you may provide any custom equality function.
    
    const treats = useStore(
      (state) => state.treats,
      (oldTreats, newTreats) => compare(oldTreats, newTreats)
    )
    

    src: https://github.com/pmndrs/zustand#recipes