Are there best practices for optimizing PHP code to prevent menu "blinking" when reloading?

When a menu "blinks" or reloads when the page is refreshed, it is usually due to inefficient code that causes the menu to be reloaded each time the page is accessed. To prevent this, you can optimize the PHP code by storing the menu data in a session variable and checking if it has already been set before reloading the menu.

<?php
session_start();

if (!isset($_SESSION['menu'])) {
    // Code to fetch and set menu data
    $_SESSION['menu'] = $menuData;
}

// Display the menu using the data stored in the session variable
echo '<ul>';
foreach ($_SESSION['menu'] as $menuItem) {
    echo '<li>' . $menuItem . '</li>';
}
echo '</ul>';
?>