Skip to content

Instantly share code, notes, and snippets.

@flucivja
Last active January 17, 2019 07:20
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 flucivja/52166f09c76a32c1aacbf6ec45e49e8c to your computer and use it in GitHub Desktop.
Save flucivja/52166f09c76a32c1aacbf6ec45e49e8c to your computer and use it in GitHub Desktop.
React useState - usage of state reference misunderstanding
// This is the example of React component using useState React Hook which looks alright at first glance but it is not.
// Someone would think that "setText" would set text variable to new text and it can be used immediatelly, but this is not true.
// The setText does not update "text" variable immediatelly, it will update text state somewhere at React internals
// and after the component rerenders the "text" variable will be updated with new value.
// This is not some React magic, this is just how setter works.
// You must remember that functional component is basically the render method of class component
// and if state is changed in render method then component must rerender to access new state.
function Text() {
const [text, setText] = useState('');
const handler = (evt) => {
// the "text" variable is not updated immediatelly.
// It will just tell React that "hey, this component new state is this" and React schedules rerender of component.
// Maybe it would be better to name setter function "scheduleTextUpdate" :)
setText(evt.target.value);
// the following function use "text" variable, but it won't be new text.
logText();
};
const logText = () => {
console.log(text); // the "text" variable here will always point to the state of the latest component render.
};
return <input type={'text'} onChange={handler} />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment