Hooks are new feature added in React 16.8 version by which we can use react features without classes
Hooks wont work inside class, Hooks should be used only in functional components.
Rules of Hooks :
- Hooks should be used only at top level of component.
- Hooks should be used only in React functional components.
- We should not call Hooks inside Loops , Nested functions.
If our business logic depends on some state, then we can make use of useStateHook.
useState will return two parameters.
- current state.
- function by which we can update that state.
useState will take one parameter , that will be the initial state.
In class-based react components side effects will be implemented in life cycle methods, this is because the render method is too early to handle these side effects.
- componentDidMount: This is executed only once in the entire component lifecycle.
- componentDidUpdate: Whenever component state changes then this lifecycle method will be executed.
so code is duplicated, as we need to perform same activity in two lifecycle methods.
so basically in class-based components
useEffect will combine these 3 lifecycle methods ( componentDidMount, componentDidUpdate, componentDidUnmount )and code duplication can be avoided.
This Hook lets you perform side effects in functional-based components.