const postType = useSelect(
( select ) => {
console.log("RUN");
return select( 'core/editor' ).getCurrentPostType();
},
[]
);
I have the above in a component. With [] I see 'RUN' 3 times. Without it I see 'RUN' 4 times.
I am trying to understand this. This is helpful - but still not 100% clear.
In both cases the actual component is rendered 3 times.
My concern is that I won't want to miss updated data by using it. In this case postType doesn't change so I feel it is safe to use it and it seems to be a small performance optimisation.
But if the data changes? I am also wrapping this:
wp.data.select('core').getEntityRecords('taxonomy', "my_taxonomy", {per_page: 100})
in useSelect - because it will be null until loaded. But - and this is the part I do not understand, if I use [] I still get the updated data. (It is null the first time and the actual data the second). So [] does not mean - only run this once. It seems to mean - "do not recreate the function passed as the first param to useSelect" - but if it is still calling that function why would you ever want it to be re-created?
Sorry - probably this is not clear and I am just failing to even grasp the most basic point here - but if anyone can explain to me (probably in fairly simple terms) what is going on, that would be fantastic.
Or at least - when should I use an empty array and when not?
Thanks
useSelect
is a custom React hook that uses react.dev/reference/react/useMemo and react.dev/reference/react/useCallback, so reading these (new) React's API reference articles might help you further.