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

97
Views
react native useState become empty when other state change

I have state like this

const [username,setUsername] = useState("")
const [password,setPassword] = useState("")
const [page,setPage] = useState("")

there is only one text input in entire page in page 1 with prev and next bottom buttons

enter user name

in page 2 with prev and next bottom buttons

enter password

but when I move from page1 to page 2 or vice verse text input field become empty.

I am just hiding textinput according to page value

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

0

If these states are part of your Page1, whenever you are switching to Page2 you are unmounting Page1 and lifetime of states is till the time Page1 is mounted. Next time you are opening Page1 that is complete new fresh Page1.

If you want states should be persisted even on unmounting of pages you can go with following approaches:

1- Lift the state up keep the states to parent component and pass the values/setter functions to the page.

const Dashboard=()=>{
            const [username,setUsername] = useState("")
            const [password,setPassword] = useState("")
            const [page,setPage] = useState("")  
            const [activePage,setActivePage] = useState(0);
            return(<div>
                  {activePage===0?<Page1  username={username} setUserName={setUserName}/>:null}
                 {activePage===1?<Page2  password={password} setPassword={setPassword}/>:null}
                <button onClick={()=>{setActivePage(value=>value-1)}}>PREV<div/>
                <button onClick={()=>{setActivePage(value=>value+1)}}>NEXT<div/>
                </div>)
            }

This way you are not unmounting parent component so state will not be on page changing.

2- Use any central state management library (redux/mobx/context)

about 4 years ago · Juan Pablo Isaza Report

0

The state will NOT stay alive longer then your component (I mean, whenever you change current page, the previous page is destructed).

What you seem to be aiming for can be called "persistent" state, or Application-wide state.

Redux is one of such persistent state implementions: https://redux.js.org/introduction/getting-started

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!