Can this react script be optimized? How to make it faster

Of course it never changes, because you told it that it never changes:

        // Selected page list
        const { initialSelectedPages, selectedPagesResolved} = useSelect(
            ( select) => {
                ....
            },
      ----->[] <-----
        );

You declared the dependencies as an empty array, and empty arrays won’t change, so this hook won’t update when your attributes update because you didn’t specify the attributes that were going to update.

E.g.

const { foo } = useSelect(
    ( select ) => {
        return { foo: bar+1 };
    },
    [ bar ]
);

Here, foo will have the value of bar + 1. That function will not run until the contents of the dependency array changed. This avoids it constantly running. The only reason foo changes when bar changes is because I declared bar as a dependency.

So when you do this:

                const selectedPagesArgs = [ 'postType', 'page', {include : attributes.onlyOn} ];

It has no idea that when attributes.onlyOn changes it has to redo this, because you did not declare it in the list of dependencies.

Note that this is similar if not the same semantics as useEffect.

Here is the official documentation with examples and explanations:

https://developer.wordpress.org/block-editor/reference-guides/packages/packages-data/#useselect