When I click on the NextButton I want to increment the value of the page state which is set to default at 0. In the header, I want to show value in the FormTitles array at index of page.
Currently, it increments for a second then instantly reverts back to the default value as can be seen in the GIF.
What is causing this issue?
import styled from "styled-components"
import { useState } from "react";
function Form() {
const [page, setPage] = useState(0);
const FormTitles = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
]
const handlePageIncrement = () => {
setPage((currPage) => currPage + 1)
}
return (
<FormWrapperOuter>
<ProgressBar></ProgressBar>
<FormWrapperInner>
<Header><h1>{FormTitles[page]}</h1></Header>
<Body></Body>
<Footer>
<PrevButton>Back</PrevButton>
<NextButton onClick={handlePageIncrement}>Next</NextButton>
</Footer>
</FormWrapperInner>
</FormWrapperOuter>
)
}
2
Answers
The reason why the page value is reverting back to the default value is because you are using the
useState
hook to set the initial value of the page state variable to 0. TheuseState
hook is an asynchronous hook, which means that the state variable will not be updated immediately when you call thesetPage
function. Instead, the state variable will be updated after the next render cycle.To fix this, you can use the
useEffect
hook to update the state variable immediately after thesetPage
function is called. TheuseEffect
hook is a synchronous hook, which means that the code inside theuseEffect
function will be executed immediately after the component is rendered.Here is the code for the
useEffect
hook:The
useEffect
hook takes two arguments: a function and an array. The function is executed whenever any of the values in the array change. In this case, the function is executed whenever the value of thepage
state variable changes.The
useEffect
hook is a powerful tool that can be used to update the state of a component immediately after a value changes. In this case, we are using theuseEffect
hook to update the value of thepage
state variable immediately after thesetPage
function is called.Here is the complete code for the
Form
component:I hope this helps! Let me know if you have any other questions.
This is what you can do:
Take a title variable that stores the value and update it when function triggers and also change this part