React Part II Flashcards
useState
allows u to add state into functional components, take into 2 arguments initial state and function that update its
[count, setCount] - react will remember the current state between renders and update the most recent one to function
what does [] means in useState ?
array destructuring, array returns a pair, current value and function to update it, same as array[0], array[1]
how to set multiple states in useState ?
This can done by using storing an object inside State
useState({a: 0, b: 0}), and updating state using spread operator setState({…a:1, b:1})
Why use Hooks over Class Components ?
Hard to reuse stateful logic between Components. (hooks allows with custom hook without changing components hierarchy)
Complex components become hard to understand (component did mount use for data fetching but can also use for even listener)
Class can be confusing: this keyword use more than other programming languages.
classes don’t minify very well, and they make hot reloading flaky and unreliable
useEffect
If we want something to happen in response to a render or just before an unmount, that something is often referred to as a side effect (or sometimes just an effect)
eg: data fetching, changing dom
same as ComponentDidmount, componentDidUpdate, componentWillUnmount
default state of useEffect
By default, React runs the effects after every render — including the first render
How to clean up useEffect ?
Cleaning up useEffect with returning a callback function.
(function subscribe to ur friend status and clean up by unsubscribing it) - same as component unmount
Rules of Hooks ?
Only call Hooks at the top level. (not inside loop, condition, nested functions) - ensure hooks are called in the same order each time a component renders
Can only call hooks from react function components. (cant be call from regular js function)
can be call - call ur own custom hooks
Why use custom hooks ?
Want to reuse some stateful logic between components (previously render prop and higher-order components) (but each state is isolated from each other)
useEffect with empty []
if you want to run effect and clean it up only once(on mount and unmount)
your effect doesnt depend on any values from props or state, so it never needs to re-run
similar to componentDidMount and
componentWillUnmount
useEffect with dependencies array [a,b]
run effect whenever the prop or state changes
Mounting
Whenever a React component gets added to the DOM
Unmounting
Whenever component is removed from the page
Component render means ?
A component renders (ie. the function is called) when it mounts, and when its props or state change. A component stops rendering when it unmounts.
useContext
Accepts a context object (the value returned from React.createContext) and returns the current context value for that context
- render when context value change