Last active
November 12, 2021 01:41
-
-
Save allenwei/03319815f7cf6e9d617a4bd8dcb28b6d to your computer and use it in GitHub Desktop.
useState with props correct way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
const Box = ({ num }) => { | |
const [state, setState] = React.useState(num); | |
React.useEffect(() => { | |
setState(num); | |
}, [num]); | |
return <div>child state ${state}</div>; | |
}; | |
const App = () => { | |
const [state, setState] = React.useState(); | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<button onClick={() => setState(Math.random(10))}>Click Me</button> | |
<div>parent state: {state}</div> | |
<Box num={state} /> | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment