Reputation: 389
I am currently working on a react native app using react query and zustand. The simplified version is a view that has a map. On top of the map is a bottom sheet which either shows a list of items or multiple screens using react navigation to add an item. I am persisting the state of each value in the form into a store using zustand. My list of items is fetched using react query. The map displays a location which either comes from the first item in the list or when the user chooses a location when adding a new item.
I am currently deriving the camera position of the map with a custom hook looking like this.
export const useMap = () => {
const formLocation = useFormStore((state) => state.location);
const { data } = useList();
const currentCamera = {
center: {
latitude: 0,
longitude: 0,
},
pitch: 0,
heading: 0,
altitude: 100000000,
zoom: 0,
};
if (formLocation) {
currentCamera.center = formLocation;
currentCamera.altitude = 1000;
}
if (data && data.length > 0) {
currentCamera.center = data[0].location;
currentCamera.altitude = 1000;
}
return { currentCamera };
};
Since i normally only work with angular i am wondering if it is a good practice to compose hooks like this.
I feel like the state is pretty scattered. Since these hooks are only used for one screen i get the itch to colocate everything into one single hook.
Upvotes: 0
Views: 467
Reputation: 386
I would like to suggest different approach.
Hooks are fine but it makes your code react dependent. It can make hard to solve performance problems. Leads you write lots of useMemo, useCallback...
What you are doing is calculating a derived state, but also using a variable from a hook (which makes me unsure about this suggestion)
in useFormStore
, create a setter function for location
. Let's call it setLocation
in setLocation
, call calculateCurrentCamera
which is just a plain js function.
The only problem can be is, you need to pass data
to store function where you set location
function calculateCurrentCamera(formLocation, data){
const currentCamera = {
center: {
latitude: 0,
longitude: 0,
},
pitch: 0,
heading: 0,
altitude: 100000000,
zoom: 0,
};
if (formLocation) {
currentCamera.center = formLocation;
currentCamera.altitude = 1000;
}
if (data && data.length > 0) {
currentCamera.center = data[0].location;
currentCamera.altitude = 1000;
}
}
you can check storing, calculating derived state for zustand from this thread: https://github.com/pmndrs/zustand/issues/132
Upvotes: 0