Introduction
Available after react 16.8
React Hooks are used in functional components to manage state.
useState
returns an array with exactly two elements. First element is the state, the second element is a function that will allow us to update the state, and re-render the DOM.
Important The returned function by useState
doesn’t work exactly like setState
, as it doesn’t automatically merge the updated value with other values not mentioned in the function, rather, it replaces the original one with an entirely new one.
1 | import React, { useState } from 'react'; |
Concept
Functional with Hooks: hooks enable functional components to have class-only functionalities.
Available after react 16.8
useState()
1 | // Todo.js |
Array Destructure and Multiple state. (Better practice)
1 | const [todoName, setTodoName] = useState(''); |
Use state as an object
1 | const [todoState, setTodoState] = useState({userInput: '', todoList: []}); |
All the hooks can only be called at the top(root) level in the component.
useEffect()
useEffect()
accepts two arguments:
- A function as argument which runs when the component runs at the first time. It make sure the function is executed after the render cycle is finished.
- An array of values we want to have a look at before running the function. Only the value in the array has changed do we want to run again the function.
Runs after every render cycle.
1 | import {useEffect} from 'react'; |
Imitate componentDidMount()
1 | useEffect(() => {}, []) // Only run once |
Imitate componentDidMount()
and componentDidUpdate()
1 | useEffect(() => {}, [someState]) // Only run once |
Cleanup1
2
3
4
5
6useEffect(() => {
document.addEventListener('mousemove', mouseMoveHandler);
return () => {
document.removeEventListener('mousemove', mouseMoveHandler);
}
}, []); // Add eventlistener when component is mount, and remove listener when component is unmount
Custom Hooks
- name convention: start with
use
1 | import { useState } from 'react'; |
Use costom hooks enables to share stateful functionality through different components.
1 | import { useFormInput } from '../hooks/forms'; |
Refs in React Hooks
1 | import { useRef } from 'react'; |