title: Keep track of pagination and go back most recent last page number in react
body: <p>I am working on an ecommerce, where I am using material UI pagination component for implementing pagination. Here is new requirement arises. I need to add functionality in pagination: if user click on let's say respectively 3,7,11,13 if they click on browser back button they will go back to 11 then 7 then 3 and lastly 1. How do I do that?</p>
  <p>I am using react, react router dom.</p>
  <p>Here is pagination structure:</p>
  <p><a href="https://i.stack.imgur.com/MmC3S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MmC3S.png" alt="Pagination structure" /></a></p>
  <p>FYI, this is url and API structure:
  <a href="https://i.stack.imgur.com/n2mfO.png" rel="nofollow noreferrer">URL and API structure</a></p>
  <pre class="lang-js prettyprint-override"><code>import React, { useEffect, useState } from &quot;react&quot;;
  import { useHistory, useParams } from &quot;react-router-dom&quot;;
  import ProductList from &quot;../../components/common/ProductList/ProductList&quot;;
  import {
    GET_PRODUCTS_BY_BRAND,
    GET_PRODUCTS_BY_CATEGORY,
    GET_PRODUCTS_BY_SUBCATEGORY,
    GET_PRODUCTS_BY_VENDOR,
  } from &quot;../../requests/HomePageApi&quot;;
  import { Pagination } from &quot;@material-ui/lab&quot;;
  import &quot;./ShopPage.scss&quot;;
  
  const ShopPage = () =&gt; {
    const { type, slug, subcategory } = useParams();
    const [loading, setLoading] = useState(true);
    // const [error, setError] = useState(false);
    const [brands, setBrands] = useState([]);
    const [colors, setColors] = useState([]);
    const [sizes, setSizes] = useState([]);
    const [products, setProducts] = useState(null);
    const [filteredProducts, setFilteredProducts] = useState(null);
    const [page, setPage] = React.useState(0);
    const [count, setCount] = React.useState(1);
    const [limit, setLimit] = React.useState(60);
    const [total, setTotal] = React.useState(60);
    const [sideFilter, setSideFilter] = useState(false);
    const [vandor, setvandor] = useState({
      vendorImg: &quot;&quot;,
      vendorName: &quot;&quot;,
      vendorSlug: &quot;&quot;,
    });
  
    const [filter, setFilter] = useState({
      // brands: &quot;&quot;,
      color: &quot;&quot;,
      size: &quot;&quot;,
      price: &quot;&quot;,
    });
  
    const closeSideFilter = () =&gt; {
      setSideFilter(false);
    };
  
    const getProducts = async (slug, qParams) =&gt; {
      try {
        let res;
  
        if (type === &quot;category&quot;) {
          subcategory
            ? (res = await GET_PRODUCTS_BY_SUBCATEGORY(
                slug,
                subcategory,
                qParams
              ))
            : (res = await GET_PRODUCTS_BY_CATEGORY(slug, qParams));
        }
  
        if (type === &quot;brand&quot;) res = await GET_PRODUCTS_BY_BRAND(slug, qParams);
        if (type === &quot;store&quot;) res = await GET_PRODUCTS_BY_VENDOR(slug, qParams);
  
        if (res) setLoading(false);
  
        if (res &amp;&amp; res.products &amp;&amp; res.products.length &gt; 0) {
          setProducts(res.products);
          setFilteredProducts(res.products);
          setTotal(res.total);
          setCount(Math.ceil(res.total / limit));
  
          if (type === &quot;brand&quot;) {
            setvandor({
              vendorImg: `/assets/images/brand/${res.products[0].brand_logo}`,
              vendorName: res.products[0].brand_name,
              vendorSlug: res.products[0].brand_slug,
            });
          } else if (type === &quot;store&quot;) {
            setvandor({
              vendorImg: `/assets/images/brand/${res.products[0].brand_logo}`,
              vendorName: res.products[0].shop_name,
              vendorSlug: res.products[0].vendorSlug,
            });
          }
  
          if (res.colors) {
            const uniqueColors = [...new Set(res.colors)];
            setColors(uniqueColors);
          }
  
          if (res.sizes) {
            const uniqueSizes = [...new Set(res.sizes)];
            setSizes(uniqueSizes);
          }
  
          // if (res.brands) setBrands(res.brands);
        }
      } catch (error) {
        console.log(error);
      }
    };
  
    // console.log({ filteredProducts, filter, page, count, limit, total });
  
    React.useMemo(() =&gt; {
      let qParams = {
        page: page,
        limit: limit,
        size: filter.size,
        color: filter.color,
        // brands: filter.brands,
        price: filter.price.length ? `${filter.price[0]},${filter.price[1]}` : &quot;&quot;,
      };
  
      if (slug) {
        getProducts(slug, qParams);
      }
    }, [slug, page, limit, filter, count]);
  
    React.useEffect(() =&gt; {
      setPage(0);
    }, [filter]);
  
    const changeLimit = (limit) =&gt; {
      setPage(0);
      setLimit(limit);
    };
  
    const handleChange = (event, value) =&gt; {
      // window.scrollTo({ top: 0, left: 0, behavior: &quot;smooth&quot; });
      setPage(value - 1);
    };
  
    const slugTitle = (slug) =&gt; slug.split(&quot;-&quot;).join(&quot; &quot;);
  
  
    return (
      &lt;FadeTransition&gt;
        {/* {loading &amp;&amp; (
          &lt;div className=&quot;section-big-py-space ratio_asos py-5&quot;&gt;
            &lt;div className=&quot;custom-container&quot;&gt;
              &lt;Skeleton type=&quot;ShopPage&quot; /&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        )} */}
  
        {!loading &amp;&amp; products === null &amp;&amp; (
          &lt;div className=&quot;section-big-py-space ratio_asos py-5&quot;&gt;
            &lt;div className=&quot;custom-container&quot;&gt;
              &lt;h3 style={{ color: &quot;#32375A&quot;, textAlign: &quot;center&quot; }}&gt;
                Sorry, No Product Found!
              &lt;/h3&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        )}
  
        {products &amp;&amp; (
          &lt;div className=&quot;title-slug-section&quot;&gt;
            &lt;h2 class=&quot;title-slug&quot;&gt;{slug &amp;&amp; slugTitle(slug)}&lt;/h2&gt;
          &lt;/div&gt;
        )}
  
        {products &amp;&amp; (
          &lt;section className=&quot;section-big-py-space ratio_asos&quot;&gt;
            {/* {type !== &quot;category&quot; &amp;&amp; (
              &lt;div className=&quot;merchant-page-header&quot;&gt;
                &lt;div className=&quot;custom-container&quot;&gt;
                  &lt;div
                    className=&quot;shadow-sm bg-white rounded p-3 mb-5 d-flex align-items-center w-100&quot;
                    style={{ minHeight: &quot;132px&quot; }}
                  &gt;
                    &lt;div className=&quot;row align-items-center w-100&quot;&gt;
                      &lt;div className=&quot;col-lg-6&quot;&gt;
                        &lt;div className=&quot;row align-items-center&quot;&gt;
                          {vandor &amp;&amp; vandor.vendorImg &amp;&amp; (
                            &lt;div className=&quot;col-auto&quot;&gt;
                              &lt;Image
                                src={vandor.vendorImg}
                                alt={vandor.vendorName}
                                className=&quot;img-fluid merchant-img&quot;
                              /&gt;
                            &lt;/div&gt;
                          )}
                          &lt;div className=&quot;col-auto mt-lg-0 mt-2&quot;&gt;
                            &lt;h3 className=&quot;mb-0&quot;&gt; {vandor.vendorName} &lt;/h3&gt;
                          &lt;/div&gt;
                        &lt;/div&gt;
                      &lt;/div&gt;
                     
                    &lt;/div&gt;
                  &lt;/div&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            )} */}
            &lt;div className=&quot;collection-wrapper&quot;&gt;
              &lt;div className=&quot;custom-container&quot;&gt;
                &lt;div className=&quot;row&quot;&gt;
                  &lt;div className=&quot;col-sm-3 collection-filter category-page-side&quot;&gt;
                    {/* &lt;SidebarFilter
                      type={type}
                      brands={brands}
                      colors={colors}
                      sizes={sizes}
                      onChange={(data) =&gt; setFilter(data)}
                    /&gt; */}
  
                    &lt;InnerCategory /&gt;
  
                    {products &amp;&amp; (
                      &lt;RowSlider title=&quot;New Products&quot; products={products} /&gt;
                    )}
                  &lt;/div&gt;
                  &lt;div className=&quot;collection-content col-lg-9&quot;&gt;
                    &lt;div className=&quot;page-main-content&quot;&gt;
                      &lt;div className=&quot;collection-product-wrapper&quot;&gt;
                        &lt;div className=&quot;row&quot;&gt;
                          &lt;div className=&quot;col-xl-12&quot;&gt;
                            {/* &lt;Button
                              variant='contained'
                              className='bg-dark text-light d-lg-none mb-3 mt-2 w-100'
                              onClick={() =&gt; setSideFilter(true)}
                            &gt;
                              &lt;span className='filter-btn  '&gt;
                                &lt;i
                                  className='fa fa-filter'
                                  aria-hidden='true'
                                &gt;&lt;/i&gt;
                                Filter
                              &lt;/span&gt;
                            &lt;/Button&gt; */}
                          &lt;/div&gt;
                        &lt;/div&gt;
  
                        &lt;MainFilter
                          type={type}
                          // brands={brands}
                          colors={colors}
                          sizes={sizes}
                          page={page}
                          limit={limit}
                          onCountChange={(c) =&gt; changeLimit(c)}
                          onChange={(data) =&gt; setFilter(data)}
                        /&gt;
  
                        {/* &lt;TopFilter
                          onCountChange={(x) =&gt; changeLimit(x)}
                          total={total}
                          page={page}
                          limit={limit}
                          setSideFilter={setSideFilter}
                        /&gt; */}
  
                        {filteredProducts &amp;&amp; (
                          &lt;ProductList products={filteredProducts} /&gt;
                        )}
  
                        {count &gt; 1 &amp;&amp; (
                          &lt;div className=&quot;d-flex justify-content-center mt-4&quot;&gt;
                            &lt;Pagination
                              count={count}
                              page={page + 1}
                              onChange={handleChange}
                              shape=&quot;rounded&quot;
                            /&gt;
                          &lt;/div&gt;
                        )}
                      &lt;/div&gt;
                    &lt;/div&gt;
                  &lt;/div&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/section&gt;
        )}
  
        {!loading &amp;&amp; products?.length === 0 &amp;&amp; (
          &lt;div className=&quot;merchant-page-header&quot;&gt;
            &lt;div className=&quot;custom-container pt-5&quot;&gt;
              &lt;div
                className=&quot;shadow-sm bg-white rounded p-3 mb-5 d-flex align-items-center justify-content-center w-100&quot;
                style={{ minHeight: &quot;132px&quot; }}
              &gt;
                &lt;h3 className=&quot;mb-0&quot;&gt;No Products found!&lt;/h3&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        )}
  
        &lt;Drawer
          open={sideFilter}
          className=&quot;add-to-cart&quot;
          onClose={() =&gt; setSideFilter(false)}
          transitionDuration={400}
          style={{ paddingLeft: &quot;15px&quot; }}
        &gt;
          &lt;SidebarFilter
            onClose={closeSideFilter}
            type={type}
            // brands={brands}
            colors={colors}
            sizes={sizes}
            onChange={(data) =&gt; setFilter(data)}
          /&gt;
        &lt;/Drawer&gt;
      &lt;/FadeTransition&gt;
    );
  };
  
  export default ShopPage;
  
  </code></pre>