I am working on developing a new blog app with Next.js.
In the current layout of the blog, I have successfully fetched data for my sidebar (to display "recent posts") using the useEffect/fetch method, as getInitialProps only works on Pages. However, this causes the data to reload every time I switch between pages, resulting in a momentary blank screen and post title reloads.
Is there a way to prevent this behavior after the initial load and maintain a constant or something similar? I tried using the "[]" method but it didn't solve the issue:
const [posts, setPosts] = useState([])
useEffect(() => {
const fetchData = async () => {
const res = await fetch('/api/posts');
const {data} = await res.json();
setPosts(data)
}
fetchData()
}, []);
Alternatively, is there a better approach to fetching data for my sidebar? This solution I implemented is functional but not without its drawbacks.