How to use with a React class component? #295
-
What is the general technique for consuming Zustand within a class component in React? My first (gross) attempt:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 8 replies
-
It looks good. |
Beta Was this translation helpful? Give feedback.
-
Zustand uses hooks, so in Class components you can work with the instance itself, using the built-in Zustand Store: import create from "zustand";
export interface ExampleStore {
exampleString: string;
setString: (x: string) => void;
}
export const useExampleStore = create<ExampleStore>((set) => ({
exampleString: "",
setString: (x) => set(() => ({ exampleString: x })),
})); React Class Component: import { useExampleStore } from "./exampleStore";
class ExampleComponent extends Component {
render() {
return (
<div>
<div>{useExampleStore.getState().exampleString}</div>
<button
onClick={() => {
useExampleStore.setState({ exampleString: "Hello Zustand!" });
}}
>
Update the string!
</button>
</div>
);
}
} |
Beta Was this translation helpful? Give feedback.
-
This function works like import React, {Component} from 'react'
import {useShallow} from 'zustand/react/shallow'
export const zustandConnect = (useStore, selector) => {
return Component => (
React.forwardRef(
(props, ref) => (
<Component
ref={ref}
{...props}
{...useStore(useShallow(selector))}
/>
)
)
)
} usage const mapStateToProps = ({setName, setDate, date}) => ({
setName,
setDate,
date
})
export default zustandConnect(useTestStore, mapStateToProps)(TestComponent) |
Beta Was this translation helpful? Give feedback.
It looks good.