For all $n\ge 4$, the optimal number of squares is $2(n-1)$.
A construction, taken from Jorik's answer, is as follows.
If $n$ is even,
$n-2$ squares have lower left corner $(0,0)$, whose widths comprise all integers between $1$ and $n-1$ except for $n/2$.
$n-2$ squares have upper right corner $(n,n)$, with these same widths.
Two squares have width $n/2$. One has its lower right corner at $(n,0)$, the other has its upper left corner at $(0,n)$.
If $n$ is odd,
$n-3$ squares have lower left corner $(0,0)$, whose widths comprise all integers between $1$ and $n-1$ except for $(n-1)/2$ and $(n+1)/2$.
$n-3$ squares have upper right corner $(n,n)$, with these same widths.
Two squares have width $(n-1)/2$. One has its lower right corner at $(n,0)$, the other has its upper left corner at $(0,n)$.
Two squares have width $(n+1)/2$. One has its lower right corner at $(n,0)$, the other has its upper left corner at $(0,n)$.
Here is a proof that this is optimal, taken from joriki's answer.
Consider the $4(n-1)$ unit line segments in the grid which have one endpoint on the outside of the grid and the other endpoint inside the grid. Each square can cover at most two of these line segments. Therefore, in order to cover all of them, you need at least $4(n-1)/2=2(n-1)$ squares.