React Hooks Flashcards
What are the 2 values that goes into useState()?
setState returns an array with two values. We can use destructuring to take those out.
EX: const [count, setCount] = useState(0)
The first one is what we want the initial value of the state to be, so basically the this.state.
The second one is the function that will be called to change the state, or the this.setState
How would you call the state values to use them in code?
Unlike class components where you need this.state. whatever it is you need, here we just use the name we’ve given the state. so in our very first example we use destructuring to take out the value. const [count, setCount] = useState(0). Now if we want to use count which is the original state, we can just do {count} where we need ti. No need to bind this or specify state.
What is the real benefit of Hooks? What’s an example?
Code reusability. We can share stateful logic between components. Also with class components state lives in the constructor. This could lead to a complex stream of nested components.
Part 1 of useToggle. In the course, he shows us an example of toggling state and why toggling state true and false with just functions is difficult. Explain why this is the case
A very common use case is toggling piece of state from true to false. In his example we have 2 state values. In the h1 we have a onClick that triggers a function but the problem is that we’d need to create 2 seperate functions to do the same thing due to both of them setting the opposite value for their own state.
We have:
const [isHappy, setIshappy] = useState(true)
const [isHeartBroken, setIsHeartBroken] = useState(false)
Now in the div we create 2 h1’s and both of them have an onClick but the problem is that each one only toggles it’s own.
const toggleIsHappy = () => { setIsHappy{!isHappy}; }
Toggle part 2. He creates a useToggle hook (seperate file) which will be called in the toggler.js. Explain the steps to creating a hook that toggles the state. Code example is included
We create useToggle function in new file which will take an argument which will be the initial value, so whether we want isHappy to be true/false in the toggler.js file.
He then creates a arrow function called toggle which simply takes setState and sets it equal to !state. We then return an array which is the conventional way of doing it with the piece of state and toggle instead of setState.
function useToggle(initialVal) { const [state, setState] = useState(initialVal); const toggle = () => {setState{!state}; } return [state, toggle];
What is the rule of React Hooks?
Only call them in the top level of the functional component. They don’t work in regualr JavaScript functions, nested functions, loops, or anything like that. Only exception to this rule is custom hooks.
What is useEffect?
Takes a function we define as its first argument. React will then run the function anytime stateful data changes in the component. Means it will run once when the component is initialized with default value then again each time state is updated.
function btn() { const [count, setCount] = useState(0) const [loaded, setLoaded] = useState(false)
// This code will be run after react has updated the dom. In current example it will run this function anytime stateful data changes on a component. useEffect(() => { alert("Hello") })
Give an example of when we’d use useEffect with fetch
We need to fetch data when a component is first initialized, then update the state asynchronously after the data has been fetched.
const [loaded, setLoaded] = useState(false);
useEffect(() => {
fetch(‘foo’).then(() => setLoaded(true) )
})
The example this guy is using regarding true/false would just run forever because everytime we do a fetch we update the state which then triggers another fetch and so on forever. Solution to this is the second parameter.
What is the second argument in useEffect
it is an array of dependencies. If we add an empty array that means there are no depenedencies and it’ll only run once when the component is first initialized.
In other cases we might want to rerun the function anytime certain stateful data has changed. We can do that by adding the state to the dependencies array. Now React will track that value and anytime it changes it will rerun this function.
const [loaded, setLoaded] = useState(false);
useEffect(() => {
fetch(‘foo’).then(() => setLoaded(true) )
}, [count])
What isa teardown function and how would you make one?
This runs when the component is destroyed. The way we use it is to return a function from our useEffect callback. React will take the function returned here and call it when the component is destroyed.
useEffect(() => {
alert(‘Hello side effect’);
return () => alert(‘Goodbye Component’)
What is useContext?
Allows us to work with React’s context API which shares data without passing props.
const moods = {
happy: smiling emoji
sad: crying emoji
}
/*We create a context to show the current mood across multiple disconnected components*/ const MoodContext = createContext(moods)
return ( /*One part of the application may be happy so we use a context provider to scope the happy mood there*/
// Any child component inside of it can inherit that value without needing to pass props down the children
)
This now brings us to the useContext hook. It allows us to access or consume the current value from the context provider which may look many levels higher in the component tree function moodEmoji() { const mood = useContext(MoodContext);
return <p>{mood}</p>
}
useEffect is like a combination of what?
Allows us to implement logic for all of the lifecycle methods within a single function api. Acts as a combination of the lifecycle methods. Will run after every single render.