Skip to content

Instantly share code, notes, and snippets.

@allenwei
Last active November 12, 2021 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allenwei/03319815f7cf6e9d617a4bd8dcb28b6d to your computer and use it in GitHub Desktop.
Save allenwei/03319815f7cf6e9d617a4bd8dcb28b6d to your computer and use it in GitHub Desktop.
useState with props correct way
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