1

I'm using zustand in a project with Nextjs and have an issue with next/router. Currently with my zustand setup I cannot destructure router from useRouter so I'm importing the Router object directly to use Router.push after fetching some data. This worked in every project I've created up until using the app directory, is there a solution to this?

// my zustand store

import Router from 'next/router'
import create from 'zustand'

const store = (set, get) => ({
// some state

// some actions
startGame: async () => {
 // fetch some data then navigate

 Router.push('/gamePage')
},
})

const useStore = create(store)

export default useStore;

It produces the error:

Error: No router instance found. You should only use "next/router" on the client side of your app.

To navigate to '/gamePage'

frost2709
  • 131
  • 1
  • 5

1 Answers1

1

When within the app directory you need to import the new app router from next/navigation.

The exported useRouter hook can only be used in a client side component so if you want to use it, structure your component as follows:

"use client";

import { useRouter } from "next/navigation";

function MyComponent() {
  const router = useRouter();
  return <button onClick={() => router.push("/my-page")} />;
}

More information about the new router can be found inside the official documentation.

Fabio Nettis
  • 1,150
  • 6
  • 18
  • In the new next/navigation it doesn't expose a Router object like next/router, only a useRouter hook which means it must be used in a react component, whereas Router could be used without invoking a hook which is the behavior I need. – frost2709 May 16 '23 at 20:42
  • This behavior can not be replicated in Next.js 13 at the time of this writing. – Fabio Nettis May 17 '23 at 05:40