React.js: Summary on React Hooks
React hooks: React hooks have brought some great advantages and included in react since version 16.8. React hooks can make element reusable, easy to read. To use hooks we don’t need to break any rules of react. It just make us job easier. There are three types of hooks exist in react- state hook, effect hook and custom hook. I will try to give a description in a nutshell below:
State hook: This hook ( defined by ‘useState’ in react) is used for rendering data dynamically, used in a react function components. It is a built-in hook. We have to import useState from react to react component to use it. useState contains one argument- initial state. useState returns an array with a pair. The first thing of this pair is the current state value and the second is a function that will update this current state value.
Example: const [state, setState] = useState(0);
Here ,the initial state is 0 . It can be a string or object or array or anything else. That means if there is no function to update the initial state will shown as default . The ‘state’ wil express the current state of this function. The ‘setState’ updates the state.
Effect hook: This hook operation also called side effects cause it can effect other component and won’t be done while rendering. As it is a built-in hook, we have to import useEffect from react to react component. By calling useEffect, we make react app able to run our effect function. We have to use useEffect to fetching data, setting up a subscription, changing the DOM in react component manually. Effect hook is more complex to understand than other hooks for beginners. But it is easier to use than understand.
Example: If we want to fetch data then-
useEffect(()=>{
//fetch your require data
}, [])
Custom hook: useState and useEffect are react built-in hooks. We can also create custom hook for our own purpose. Custom hook’s name starts with ‘use’. As it is a custom thing the binding is less. We can use argument as our own wish.
Rules of using hooks: The first mandatory rule is not to use hooks into of loops, conditions or nested functions. We have to use react hooks at the top level of components. The second mandatory rule is to call hooks from only react functions.