Last active
February 9, 2019 22:47
-
-
Save gregnb/561790d458dd6583757ad06c2d18c799 to your computer and use it in GitHub Desktop.
React Hooks - Notes
This file contains hidden or 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
// useState(): | |
Note: "However, unlike this.setState in a class, updating a state variable always replaces it instead of merging it." | |
/* before - example 1 */ | |
constructor(props) { | |
super(props); | |
this.state = { | |
count: 0 | |
}; | |
} | |
/* before - example 2 */ | |
state = { | |
count: 0 | |
}; | |
/* after w/ hooks */ | |
const [count, setCount] = useState(0); | |
// useEffect(): | |
/* run on mount and unmount */ | |
useEffect(() => { | |
console.log('mounted'); | |
return () => console.log('unmounting...'); | |
}, []) // <-- add this empty array here | |
/* run on every render */ | |
useEffect(async () => { | |
// whatever inside | |
}); // <-- no argument provided | |
/* run only on a prop change | |
function SomeComponent({ id }) { | |
useEffect(async () => { | |
// whatever inside | |
}, [id]); // <-- only call when `id` has changed | |
} | |
// useRef(): | |
"it can be used like instance properties on a class" | |
https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables | |
https://twitter.com/ken_wheeler/status/1088227070545719297 | |
https://stackoverflow.com/questions/53024496/state-not-updating-when-using-react-state-hook-within-setinterval | |
loops: | |
https://stackoverflow.com/questions/53906843/why-cant-react-hooks-be-called-inside-loops-or-nested-function | |
https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889 | |
state management & hooks: | |
https://blog.usejournal.com/react-hooks-the-rebirth-of-state-management-and-beyond-7d84f6026d87 | |
Notes: | |
Imagine something as simple as toggling a boolean which tends to get rewritten over and over across many components. Here we could make a hook | |
function App() { | |
const {on, toggle} = useToggle() | |
return ( | |
<button onClick={toggle}>{on ? 'on' : 'off'}</button> | |
) | |
} | |
"My personal summary is that new context is ready to be used for low frequency unlikely updates (like locale/theme). It's also good to use it in the same way as old context was used. I.e. for static values and then propagate updates through subscriptions. It's not ready to be used as a replacement for all Flux-like state propagation." | |
https://github.com/facebook/react/issues/14110 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment