React Hooks
- Only use at top level of function
- Call hooks from function components or custom hooks
- Don't use hooks in conditions, loops or event handler
- useState
Used to manage component state in a functional component
const Counter = () => {
const [count,setCount] = useState(0);
function increment(){
setCount(count+1);
}
return (
<div>
<h2>{count}</h2>
<button onClick={increment}>+</button>
</div>
)
}
- useEffect
Used to add side effects in a component. Side effects include fetching data or updating the DOM
const UserList = () => {
const [users,setUsers] = useState([])
useEffect(() => {
async function fetchUSers() {
const response = await fetch('ip/api/users');
const data = await response.json();
setUsers(data)
}
fetchUsers();
},[]);
}
- useReducer
Used to store and update state, like useState. It accepts a reducer funtion and initial state
const intialState = {count:0}
const reducer123 = (state,action) => {
switch (action.type) {
case 'increment':
return {count:state.count +1};
default:
throw new Error();
}
}
const Counter = () => {
const [state,dispatch] = useReducer(reducer123,intialState);
function handleIncrement() {
dispatch({type:'increment'});
}
}
- useRef
Used to access DOM directly or to persist values between renders
const TextInput = () => {
const [value,setValue] = useState('');
const inputRef = useRef(null);
function persistValue() {
inputRef.current.value = "Persisting Value"
}
return (
<div>
<input ref={inputRef}/>
</div>
)
}
- useMemo
Memoizes(Cache) the result of a function call, so it is not recalculated unless a state has changed.
function computeValue(n) {
return n * 1234
}
const Component = () => {
const [number,setNumber] = useState(0);
const memoValue = useMemo(() => computeValue(number),[number]);
}
function changeNumber(n){
setNumber(n)
}
- useCallback
Memoizes a function instead of the result. Function then won't be recreated after every render.
const Component = () => {
const [count,setCount] = useState(0);
const increment = useCallback(() => {
setCount(count +1)
},[count])
}
- useContext
Allows a component to take in a context from a parent component. Context provides a way for
react to pass data throughout the component tree.
import localeContext from './localeContext'
const Component = () => {
const {data} = useContext(localeContext);
}
- Custom Hooks
You can create your own custom hook and share it across to multiple components. Usually has "use" prefix
const useWhatever = (params) => {
const [data,setData] = useState(params);
const [data2,setData2] = useState(null);
return {data,data2}
}
const Component = () => {
const {data,data2} = useWhatever("params")
}