React Hooks
In the Previous versions of React, stateful logic was tied to a class based component. While it may get the job done, it would lead to a tree of nested components, which may not be the cleanest or most efficient way to write code.
useState is one of the most used react hooks. useState is used to handle changes made to state.
import {useState} from 'react';function App(){//Right Hand side
//useState takes one optional argument which sets default state.(0)//Left Hand side
//this function returns an array of two values to later use in your component. We destructure that array to assign the variables "count" and "setCount" const[count, setCount] = useState(0)
return(<div>{count}</div>);
}
We can name our left hand values anything as long as we remember that the first value is the reactive value and the second value is the setter. If the first value is utilized and changed, the UI will update and show the latest value. The second value will be used to set the first value such as an onClick.
useEffect is quite popular as well. useEffect is for side effects. use effects utilizes react life cycle events. useEffect tells React that your component needs to do something after render.
import React, { useState, useEffect } from 'react';function Example() {// this line of code will run when after the DOM is loaded. useEffect(() => { alert("hello effect!"; });const[count, setCount] = useState(0)
return(<div>{count}</div>);
}
Additional to running after the DOM is loaded the that line of code will also update as the stateful changes are made. We can return a function from our useEffect callback in order to clean up after it. In the example me above we just add one line of code like so…
import React, { useState, useEffect } from 'react';function Example() {// this line of code will run when after the DOM is loaded.
useEffect(() => { alert("hello effect!");
return () => alert('goodbye effect!")});const[count, setCount] = useState(0)
return(<div>{count}</div>);
}
useContext is one of my favorite hooks. useContext allows us to share and access data without passing props down from/to multiple children. Similar to the uses of Consumer
useContext is often viewed as the replacement.
const theme = useContext(ThemeContext);