At this point in our code, we have working module state that is similar to Zustand. If you look closely at the code you’ll notice that we are defining actions in our components. This works for some but you might want to define those actions when you create a store.
We will modify createStore
to accept a createState
function and use that function to initialize and update our state. This allows us to define actions while creating a store. We can use those defined actions in our components without having to implement any logic inline.
Instructor: [0:00] Our library code consists of createStore function to create a store, with a module state and useStore hook to use that store. Our counter app uses that library code. We create a store with count.one and count.two properties, and CounterOne and CounterTwo components. The App component is to render those components, and clicking the button increments the count numbers.
[0:28] If we look closely at the code, our components define action functions, like enq1 function in CounterOne component. While this works perfectly, it's often the case people want to define such actions close to the state in the store. To this end, we modify the createStore function a little bit. Instead of initialState, it accepts createState.
[0:54] To create initialState, we invoke the createState function with setState. We also change the useStore hook to use function update for useState, and to just return the value instead of the tuple. That's it for the library code.
[1:15] Based on the change, we modify our store creation code. We pass a function instead of a state object. The function takes setState. Using this setState function, we define enq1 and enq2 functions. The code is mostly the same.
[1:32] Now, in the CounterOne component, we use the useStore hook to get the CounterOne value and the enq1 function. The rest of the code is kept the same. The CounterTwo component is changed, likewise. The behavior of this app is exactly the same.
[1:59] What did we do? We changed the createStore function to accept a createState function, and to invoke it with setState. This allows us to define actions when creating a store. In components, we can just use the defined actions.