State management simplified with zustand


zustand is a small, fast and scalable state management package that you can use with your react applications, it can be used as your data store within your PCF control.
Below are the benefits of using it,
- Bundle size is 1.17 kb!
- Avoid props inheritance between your components
- Simplify the functions implementations for maintaining data across the control.
- Provides hooks to use the data store which handles re-renders
- Store can be called outside functional components
In our case in index.ts to get data in the getOutputs method
Check how to use it below,
Creating your data store
After initiating your control, create your store
//if you're using typescript, it would be better to set the type of the store
type PcfState= {
vars: any[]; //data object
add: (newVar: any) => void; //add function
set: (vars: any[]) => void; //set function
update: (_var: any) => void; //update function
remove: (schema: number) => void; //remove function
clear: () => void; //clear function
};
// the store below, holds the data objects and the functions related
const usePcfStore = create<PcfState>((set, get) => ({
vars: [],
//get().vars returns the current state of vars array
//set() sets the state of the store properties
add: (newVar: any) => set({ vars: [...get().vars, newVar] }),
set: (vals: any) => set({ vars: vals }),
update: (_var: any) =>
set({
vars: get().vars.map((_obj: any) => {
if (_obj.id === _var.id) {
_obj = _var;
}
return _obj;
}),
}),
remove: (id: number) =>
set({
vars: get().vars.filter((x) => x.id !== id),
}),
clear: () => set({ vars: [] }),
}));
export default useVarsStore;
Use the store hook in your component
const { add, set, vars, remove, update } = usePcfStore();
You can easily use the data store functions just like that
set(newVars);
and you get the data object like that
let _obj = vars; //just like that
Get the store data in the getOutputs method
//easy as this!
public getOutputs(): IOutputs {
return {
bindProperty : usePcfStore.getState().vars
};
}
Hope this makes it easier for you in your PCF development.
Subscribe to my newsletter
Read articles from Ahmad Sammour directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ahmad Sammour
Ahmad Sammour
๐ I am a Low code/no code enthusiast with 7+ years of experience in ๐๐ข๐๐ซ๐จ๐ฌ๐จ๐๐ญ ๐๐จ๐ฐ๐๐ซ๐๐ฅ๐๐ญ๐๐จ๐ซ๐ฆ, ๐๐ฒ๐ง๐๐ฆ๐ข๐๐ฌ ๐๐๐ business apps and experience in other platforms and technologies. I help companies deliver solutions with a real business impact. Drove implementations for satisfied clients by โฌ๏ธ ๐ข๐๐ญ๐๐ข๐๐ฏ๐๐ฃ๐ ๐ซ๐๐ก๐ช๐, โฌ๏ธ ๐ข๐๐ฃ๐๐ข๐๐ฏ๐๐ฃ๐ ๐ง๐๐จ๐ with a focus on delivering business value, decreasing technical debt and ability to cope with rapid market changes.