title: How to NOT persist state between Next.js dynamic routes?
body: <p>I'm building a headless eCommerce site using React/Next and have a <code>[product].js</code> dynamic route which is used to generate all product pages, using <code>getStaticPaths()</code> and <code>getStaticProps()</code> which generates the pages fine.</p>
  <p>I'm using <code>useState</code> hook within <code>[product].js</code> to manage a number input (for quantity) and a couple of other things.</p>
  <p>The first product page loaded works fine, but when I go to other product pages, they use the same state from the first product.</p>
  <p>Is there a way to have the state NOT persist between route changes?</p>
  <p>Through some digging, I found that this is an issue with next and is in their backlog. It essentially stems from the fact that the component doesn't have a key. This means switching between routes on the same dynamic route doesn't register correctly and causes the component to use stale state.</p>
  <p>A possible solution I found was this:</p>
  <pre><code>export async function getStaticProps({params}) {
      const props = await getData(params);
  
      // key is needed here
      props.key = data.id; 
  
      return {
          props: props
      }
  }
  </code></pre>
  <p>This is my implementation which doesn't work for me:</p>
  <pre><code>export default function ProductPage(props) {
  
    // this state doesn't reset between dynaic route changes
    const [quantity, setQuantity] = useState(1)
  
    return(
      ...
    )
  }
  
  export async function getStaticProps({ params }) {
    const slug = params.product
    const props = await client.query({
      query: singleProductQuery,
      variables: { id: slug }
    })
  
    props.key = props.data.product.slug
  
    return {
      props: props
    }
  }
  </code></pre>
  <p>I tried wrapping the contents within another component and adding a key to that, like so:</p>
  <pre><code>return(
    &lt;OuterComponent key={props.id}&gt;
      // components within here, that have their own state, now work
    &lt;/OuterComponent&gt;
  )
  </code></pre>
  <p>Since this new keyed component is only in the return statement and does not encapsulate the state hook, it does not work. This does reset the state however, for any components found within wrapped component.</p>