Posted by Sahil Pate on Sat, 15/05/2021
Recently, use of React has been increased in Web Design. Developers are using class based components in React which is quite hard to understand. Now, React has introduced Hooks in React 16.8 which lets you use state and other React features without using a class. Hooks are simply a function. Stateful logic can be re-used by hooks without changing component hierarchy. The best feature of hooks is you can create your Own Hooks. Hooks are the easiest way to use react futures such as state, lifecycle, context. This doesn't affect previous knowledge of react. You can split a single component into smaller functions based on related components. Classes act as barriers in learning react, which is now easier with Hooks. So if you are older with react you can try using hooks or if you are new to react, you can directly start learning with hooks rather than class based components.
Types of Hooks:
Basic Hooks:
It is used to declare a state variable. It is similar to this.state. It returns the current state or value and a specific function assigned to it for updating value. Function is similar to this.setState. We can declare multiple variables using useState in the same function.
This hook tells react that after rendering components needs to do something. useEffect is similar to methods such as componentDidMount,componentDidUpdate. This hook is placed inside a component. Separate API not required to read it.
It accepts the context object from the React.createContext and the current context is returned. useContext continuously renders when context value is changed.
Other Hooks:
useReducer
useCallback
useMemo
useRef
Points kept in mind while using Hooks:
Call hooks at top level only.
Call hooks from react function only
Example:
In class method, state count is initialised by setting this.state to {count: 0} in the constructor.
In the function method, there is no this we can’t assign this.state. Instead of that, we use useState hook in our component.