- Data fetching, setting up a subscription, and manually changing the DOM
- There are two common kinds of side effects in React components: those that don’t require cleanup, and those that do.
- We have to duplicate the code between these two lifecycle methods in class.
- componentDidUpdate (state-update after mounting) and componentDidMount
- useEffect - alternative way using functional style
Running some additional code after React has updated the DOM. Network requests, manual DOM mutations, and logging are common examples of effects that don’t require a cleanup.
- Setting up a subscription to some external data source.
- In that case, it is important to clean up so that we don’t introduce a memory leak!
componentDidMount() {
ChatAPI.subscribeToFriendStatus(this.props.friend.id,this.handleStatusChange);
}
componentWillUnmount() {
ChatAPI.unsubscribeFromFriendStatus(this.props.friend.id, this.handleStatusChange);
}
- The Effect Hook lets you perform side effects in function components:
useEffect(() => { document.title = `You clicked ${count} times`; });
- Each effect “belongs” to a particular render.
- effects scheduled with useEffect don’t block the browser from updating the screen.
- In the uncommon cases where they do (such as measuring the layout), there is a separate useLayoutEffect Hook with an API identical to useEffect.
- When exactly does React clean up an effect? React performs the cleanup when the component unmounts
- React also cleans up effects from the previous render before running the effects next time.
- We could return an arrow function or call it something different instead of cleanup.
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline); }
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
- React will apply every effect used by the component, in the order they were specified.
- You can tell React to skip applying an effect if certain values haven’t changed between re-renders.
- To do so, pass an array as an optional second argument to useEffect:
- If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument.
- This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.
- mdanki React_anki.md React_anki.md.apkg --deck "Everything::UnderSun::ReactJS::Hooks"