React Hooks :
React hooks are functions that let you hook into react state and life-cycle features from function components. React provides built-in hooks like useState, useEffect, useReducer, useRef, useCallback, useContext, useMemo and you can also create you own custom hooks.
React hooks are available from react version of 16.8. Before the introduction of hooks, state can be maintained only in class component not in functional component, after the introduction of hooks, state can be maintained in functional component also.
Advantages of react hooks over class component :
The main advantage of react hooks is the re-usability of stateful logic. It can be done with the help of custom hooks. Without changing component hierarchy, you can reuse stateful logic and it is easy to share custom hooks with other components.
In react class component, we split our work in different life-cycle methods like componentDidMount, componentDidUpdate and componentWillUnmount, but in hooks, we can do everything in a single hook called useEffect.
In class component, we have to use this keyword and also we have to bind event listeners, which increases complexity. This is prevented in react functional components.
React class components don’t minify very well, and they make hot reloading flaky and unreliable.
React hooks are easier to test and work with, makes the code look cleaner, easier to read and has less number of lines of code.
useState Hook :
useState hook is used to add state to a functional component.
In the above snippet, the initial value of the blogName state variable is ‘React’. Using setBlogName setter function, you can change the value of the blogName state variable.
useEffect Hook :
In class component , when the document title has to be based on counter state value, and when the document title has to updated whenever the counter value changes, we use the following code.
In the above code snippet, the codes inside componentDidMount and componentDidUpdate are relatable, but they are written in two different methods. To overcome this, we can use useEffect hook.
The above useEffect hook gets executed after every component render and whenever the count changes, it will be executed again. You can have multiple useEffect hooks in a single component, where you write relatable code inside each.
Custom Hooks :
Custom hooks is a easy way to re-use stateful logic in react hooks.
The above snippet is an example of a custom form hook, it accepts the initial value as props and sends the initial value, setter function and reset function.
You can import useInput custom hook in your component and you can use it in your component like this.
React hooks don’t replace your knowledge of react concepts. Instead, hooks provide a more direct way to use react concepts which you already know.
In future, hooks will be mostly used, and will get good support from react team.