How to make UI Grid layout work with a scrolling frame

I am trying to make an inventory system. Right now when the player opens the GUI the game loads all of the player’s items into a GUI. I use a UI grid layout to make everything look better and easier. I added a scrolling frame so that the GUI can actually fit everything. Because the inventory isn’t already in the GUI before the game is loaded the scrolling frame doesn’t fit all of the items. I found a script that updates the scrolling frame when the size of the UI layout is updated but the issue is everytime the script runs it updates the grid which makes the function run again so it updates the scrolling frame like 50 times a second which is clearly an issue. Is there a better way to update the scrolling frame, this is what I have right now.

local grid = script.Parent
local scrollingFrame = grid.Parent

local function onContentSizeChanged()
	local absoluteSize = grid.AbsoluteContentSize
	scrollingFrame.CanvasSize = UDim2.new(0, absoluteSize.X, 0, absoluteSize.Y)
end

grid:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(onContentSizeChanged)

Instead of dynamically changing the scrolling frame’s canvas size according to its contents, set its canvas size in the properties window to UDim2.new(0, 0, 0, 0) and its automatic size to ‘X’, ‘Y’ or ‘XY’, depending on the direction in which items are added.

How would I do this based on the number of items the player has. If the player has 20 items I want the game to make a perfectly sized scrolling frame to fit all the contents.