Question: I have a requirement to sort the incoming props during initial html table load of a component, and also have the ability to change the order based on button click. Although the seem to work, I am suspecting that sortArticles () just before return is not a right approach. Can you please spot the issue and recommend the right approach.

function App({articles}) {

```
const[state,setState] = React.useState(articles);  

const sortArticles = () => {
    articles.sort(function(a,b){
        return b.upvotes - a.upvotes;
    });
};

const handleUpvoteSort = () => {
    var srArticles = [...articles];
    srArticles.sort(function(a,b){
        return b.upvotes - a.upvotes;
    });
    setState(srArticles);
};

const handleDateSort = () => {
    var srArticles = [...articles];
    srArticles.sort(function(a,b){
        return new Date(b.date) - new Date(a.date);
    });
    console.log("Date sort", srArticles);
    setState(srArticles);
};

sortArticles ();
return (
    <div className="App">
        <h8k-navbar header={title}></h8k-navbar>
        <div className="layout-row align-items-center justify-content-center my-20 navigation">
            <label className="form-hint mb-0 text-uppercase font-weight-light">Sort By</label>
            <button data-testid="most-upvoted-link" className="small" onClick={handleUpvoteSort}>Most Upvoted</button>
            <button data-testid="most-recent-link" className="small" onClick={handleDateSort}>Most Recent</button>
        </div>
        <Articles articles={state}/>
    </div>
);

```

}

export default App;

Answer: 
You're right, currently sortArticles function is called on every render,
You should use an useEffect hook, so that sortArticles runs only when there's a change in articles

```
React.useEffect(()=> {
    sortArticles ();
},[ articles])

```
Realized that instead of changing the incoming props directly which might break other potential dependencies, the following seems to be reasonable a better approach.

```
useEffect(()=> {
    let srArticles = sortState(); 
    setState(srArticles);           
},[]);             
const sortState = () => {
    var srArticles = [...articles];
    srArticles.sort(function(a,b){
        return b.upvotes - a.upvotes;
    });
    return srArticles;  
};

```