React Hooks were introduced on React 16.8 by Dan Abramov, the creator of React.js
Hooks are a series of features that allows developers to use certain functionalities that were impossible in plain react function components.
We have a series of pre-defined hooks that react offers us, but we also can create our own hooks.
- useState
- useEffect
- useContext
- useReducer
- useCallback
- useMemo
- useRef
- useImperativeHandle
- useLayoutEffect
- useDebugValue
And we also will create 3 example custom hooks for our projects.
We will explain the hooks and then move into a project only using hooks.
Let's see the React.js hooks rules:
Call Hooks only on the superior level:
You can't call hooks in cycles, conditionals, or nested functionsCall Hooks only on React Functional Components or custom hooks
The list of pre-defined hooks we will explore will be:
useState
useEffect
The useEffect hooks is used on data request, subscriptions and manual actualizations. These ones are called "secondary effects"
If you're familiar with React Class Components, then, you will use the useEffect hook to handle the following lifecycle methods: componentDidMount, componentDidUpdate, componentWillUnmount.
Also, there are 2 types of secondary effects, those who requires sanitizing operation and other who don't.
Those who do not require sanitizing: Those hooks which we can execute and forget about them, for example: Network Requests, Manual DOM Mutations, Register
Those who require sanitizing: We sanitize effects that could lead to a memory leak
Effects run at every render, so we use the useEffect hook to reeplace some lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount)
Returning a function inside the useEffect to indicate react how to sanitize a effect (clean, unmount)
We usually use the useEffect with state variables.
Omiting effects to optimize rendering: If you do not want to run the effect every time the component is updated, then you should consider using the second argument of the hook, the dependency array.
const [count, setCount] = useState(0)
useEffect(()=>{
setCount(count + 1)
},[count])
This effect will run only and if only the count state variable value changes.
We can add more values to it
If we leave the dependency array empty, it will only run once
Top comments (1)
Many early birds have already started using this custom hooks library
in their ReactJs/NextJs project.
Have you started using it?
scriptkavi/hooks
PS: Don't be a late bloomer :P