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?
You would want the function to be recreated if the function was using a variable that changed. If you had something like this:
const posts = useSelect(
(select) => {
return select('core').getEntityRecords('postType', 'post', { author: authorId });
},
[],
);
Then the function is using authorId
to get the posts from a specific author. Ideally if you change authorId
then posts
should change to the posts by that author, but because it was not passed as a dependency the function will not be recreated. The original function with the original author ID will continue to be used. So by passing the variable as a dependency the posts will always reflect the correct author:
const posts = useSelect(
(select) => {
return select('core').getEntityRecords('postType', 'post', { author: authorId });
},
[authorId],
);
If you omitted the []
entirely you would also get the correct posts any time the author changed. The problem is that the function would also run when the author hadn’t changed, which is very inefficient.