I created a custom hook which contains four states. then I imported that hook into two functional components. then I was updating one of the state in the second component. but the state doesnt changed in the first component.
import React , {useState} from "react"
/** Custom hook component **/
const useApp = () => {
const[millisec , setMillisec] = useState(0)
const[sec , setSec] = useState(0)
const[min , setMin] = useState(0)
const[hr , setHr] = useState(0)
return {millisec , setMillisec , sec , setSec , min , setMin , hr , setHr}
}
export default useApp;
/** First JS FIle **/
import React from "react"
import useApp from "../App"
import Interact from "./Interact";
const Timer = () => {
const {millisec , sec , min , hr } = useApp();
return(
<>
<div>{hr}</div>
<div>{min}</div>
<div>{sec}</div>
<div>{millisec}</div>
<Interact />
</>
)
}
export default Timer
/** SECOND JS FILE **/
import React from "react"
import useApp from "../App"
const Interact = () => {
const {millisec , setMillisec , sec , setSec , min , setMin , hr , setHr} = useApp();
const handleStart = () => {
setMillisec(prev => prev +1)
return(
<>
<button onClick = {handleStart}>Start</button>
<p>{millisec}</p>
</>
)
}
export default Interact
I could Change the initial state value millisec
in the second.js file and in custom hook file but i want to change the value of millisec
in first js file as the state get changed when i click the Start button
Just pass it down:
const Timer = () => {
const { millisec, setMillisec, sec , min , hr} = useApp();
const handleStart = () => {
setMillisec(prev => prev + 1)
}
return(
<>
<div>{hr}</div>
<div>{min}</div>
<div>{sec}</div>
<div>{millisec}</div>
<Interact handleStart={handleStart} millisec={millisec} />
</>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.