Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
Why doesn't react re-render the page on button click?
function App() {
    const [users,setUsers] = useState([])

    useAsyncEffect(async () => {
        const res = await fetch('https://jsonplaceholder.typicode.com/users')
        const data = await res.json()
        setUsers(data)
    }, [])
    
    console.log(users)

    function sortCity () {
        users.sort((x,y) => {
            if(x.address.city < y.address.city) {return -1}
            if(x.address.city > y.address.city) {return 1}
            return 0
        })
        
        console.log(users)
    }

    function sortCompany () {
        users.sort((x,y) => {
            if(x.company.name < y.company.name) {return -1}
            if(x.company.name > y.company.name) {return 1}
        return 0
    })

    console.log(users)
}

<SortButton button={sortCity} text="по городу" />
<SortButton button={sortCompany} text="по компании"/>

Console logs are displayed, but it doesn't re-render.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

.sort array method mutates the state and you should avoid this. You cannot mutate anything in React, because it is not able to re-render. You should set the new state directly.

In your case you should create a new array, sort it, and set into your state:

function sortCompany () {
 const sortedUsers = [...users]

 sortedUsers.sort((x,y) => {
   if(x.company.name < y.company.name) {return -1}
   if(x.company.name > y.company.name) {return 1}
   return 0
 })

 setUsers(sortedUsers);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!