Search code examples
typescriptreduxnext.jsuse-state

Passing state from _app to pages with typescript in next.js


I have a state which I would like to set in one page and then access in another page. My solution is to create the state in _app.tsx and then pass it to each page.

My understanding is I can create the state in _app.tsx like this

function MyApp({ Component, pageProps }: AppProps) {
  const [accessToken, setAccessToken] = useState('')
  return (
    <ApolloProvider client={apolloClient}>
      <Component
        {...pageProps}
        setAccessToken={setAccessToken}
        accessToken={accessToken}
      />
    </ApolloProvider>
  )
}

How can I then access the state and setState functions in my pages? I tried

const Home: NextPage = ({setAccessToken}) => { 
...}

But I get the error: Property 'setAccessToken' does not exist on type '{ children?: ReactNode; }'.ts(2339)

How can I read the state I set in _app.tsx? Or am I going about this all wrong and should just use redux?


Solution

  • This is a typescript error that indicates that the prop setAccessToken is not expected for the Component. You can get rid of this error by updating/extending the Component interface inside AppProps. Btw what you are trying to do is very similar to the React.Context API. I would suggest using it instead of doing it yourself. You will get many advantages from doing so, like not having to send props all the way through to get/set the value on deeply nested child components.