title: Maintaining state and scroll position in react
body: <p>I'm trying to build a component that shows a list of blog posts. When a user clicks on a post, it renders the component that shows the details of the post. But when the user hits the back button in the browser, the previous component with posts list re-renders and it looses the previous state and scroll position. Is there a way that I Can save the previous state and the scroll position so that when a user hits the back button they are at the same position and the post list is not re-rendered and doesn't loose the scroll position too? </p>
  
  <p>Here's my blog list component code:</p>
  
  <pre><code>import axios from "axios";
  import { Link } from "react-router-dom";
  
  class About extends React.Component {
    state = { posts: [] };
  
    componentDidMount() {
      axios.get("https://jsonplaceholder.typicode.com/posts").then(res =&gt; {
        this.setState({ posts: res.data.slice(0, 10) });
      });
    }
  
    render() {
      const { posts } = this.state;
  
      const postsList = posts.length ? (
        posts.map(post =&gt; {
          return (
            &lt;div className="card" key={post.id}&gt;
              &lt;div className="card-body"&gt;
                &lt;Link to={"/view/" + post.id}&gt;
                  &lt;h5 className="card-title"&gt;{post.title}&lt;/h5&gt;
                &lt;/Link&gt;
                &lt;p className="card-text"&gt;{post.body}&lt;/p&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          );
        })
      ) : (
        &lt;div className="text-danger text-center"&gt;No Posts yet...&lt;/div&gt;
      );
  
      return &lt;div&gt;{postsList}&lt;/div&gt;;
    }
  }
  
  export default About;
  </code></pre>
  
  <p>Here's is my blog details component:</p>
  
  <pre><code>import React from "react";
  import { withRouter } from "react-router-dom";
  import axios from "axios";
  
  class PostDetail extends React.Component {
    state = { post: null };
  
    componentDidMount() {
      let id = this.props.match.params.post_id;
  
      axios.get("https://jsonplaceholder.typicode.com/posts/" + id).then(res =&gt; {
        this.setState({ post: res.data });
      });
    }
  
    render() {
      const post = this.state.post ? (
        &lt;div className="card border-primary"&gt;
          &lt;div className="card-header"&gt;{this.state.post.title}&lt;/div&gt;
          &lt;div className="card-body text-primary"&gt;
            &lt;p className="card-text"&gt;{this.state.post.body}&lt;/p&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      ) : (
        &lt;div className="text-center text-danger"&gt;Loading Post...&lt;/div&gt;
      );
  
      return &lt;div&gt;{post}&lt;/div&gt;;
    }
  }
  
  export default withRouter(PostDetail);
  </code></pre>