React Hooks: benefits with example
What is React Hooks?
React Hooks are functions.
React 16.8: Hooks were added as a new features in react version 16.8
Some popular built-in React Hooks
- useState
- useEffect
- useContext
- useReducer
- useCallback
- useMemo
- useRef
- useImperativeHandle
- useLayoutEffect
- useDebugValue
Benefits: Why we should use React Hooks?
Since we know there are maninly two reasons of using Class Components
- State Management
- Lifecycle Methods
So using React Hooks we can achieve similar functionality in a Functional Component.
Rules of using React Hooks
React Hooks has following rules:
- Always use Hooks at the top level of your React function components.
- Don’t call Hooks inside loops, conditions, or nested functions.
- Only Call Hooks from React function components not from regular JavaScript functions.
- Call Hooks from custom Hooks
React Hooks Example: useState and useEffect
import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); // Similar to componentDidMount and componentDidUpdate: useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${count} times`; }); return (); }You clicked {count} times