React — Hooks
--
It was in October 2019, where React announced Hooks. I though why the heck you need this. React is a great Library, no doubt about it. But you need to be updated with new functionalities. But I never regret learning and using ‘Hooks’ in React.
Before learning what ‘Hooks’ is, it is important to know the difference between Class and Functional Components.
Class Components : Till 2018, React Components were created with keyword Class. React Components are created by extending Component with render method. In Simple terms Class Components are ES6 Classes.Here the JSX needs to be returned inside the render method.
Properties (abbr. as props) can be passed and can be referred using ‘this’ keyword. You need to bind the events. For Class component maintenance, we need Life cycle methods.
Functional Component : It doesn’t required to be extended from Component a render method. They are the plain Javascript functions with returns simple HTML.
You can pass the Properties as arguments with or with out de-structuring. Since, a functional components doesn’t require ‘this’ keyword to refer props and Life Cycle methods.
In the above example, App uses GreetingsComponent as its child component and passes the name as property. GreetingsComponent receives the props and displays accordingly :
When Class components are bundled, they need to be converted to Javascript understandable Functional prototypes. This is where the Functional Components are more convenient as they are already are functions.
Note :
Life cycle methods are only used in Class Components and Hooks are only used in Functional Components.
useState :
Description :
This is same as ‘state’ in Class Components. but here the syntax is different. It returns a stateful value with the function to change the state value.
useEffect :
This hook is used for side effects. In simple terms, It effects DOM indirectly. It serves the same functionalities of class life cycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. useEffect can be cleaned up by using a return function.
Examples : updating title of the page on each navigation, fetching data, etc.,
In the above example app.js, is passing pageTitle prop to Alert Message component where it uses useEffect hook for updating the page title.
the above can be made as separate custom hook where it can be used any where. since, the above is a Synchronous update to the document title, no dependency array is required.
Notes :
- When an array is not passed, It will be called on each re render of the Component.
- 2. Pass Empty array — When empty array is passed, use Effect is only called on initial render of the page.
3. When the particular variable / prop is passed in array of useEffect, it will render, when ever the passed variable value / prop value is changed.
4. Avoid using setState in useEffect when array is not passed, because it will continuously sets the page state, and makes the page of the application in Infinite loop — making the page unresponsive.
Here, useEffect calls an API, this Asynchronous API call , calls continuously and makes the page non responsive. If you look a the info, in left side , the info number goes on increasing, this is because, useEffect is continuously calling the API and makes the page to hang on.
In order to avoid looping, Pass an empty array.
useReducer :
let’s say we have a lot of input fields in a Registration form, these input fields are dependent on the state of other input field. the using set state is cumbersome. So here we use useReducer. But this case is not compulsory, you may even use for Increment example, explained in useState hook.
In simple terms, It’s replaceable with useState.
You can use a Reducer function and can make a code splitting, so that the logic can be separate from the component. This is the standard way of writing a reducer. It is same a Reducer in Redux.
Notes :
1. useReducer is used for state management.
2. it requires two arguments, 1. function, 2. initial state
3. useReducer works pretty much same as reducer in redux, if you are familiar, it accepts two arguments a function that changes the state, and a initialState value.
4. it uses ‘dispatch’ for dispatching action to reducer with the values : Example : dispatch({type: ‘type_of_action’, value: ‘new_value_to_be_replaced’}).
here the passed object is just simple javascript object. which has a type identifier to change particular object item and a value to change, Value is always optional.
useRef :
useRef is used to create reference for html elements in react components. they are particularly used for doing some operations.
Example : Setting focus on a particular field if that is empty or the entered value is not in the regex format.
the following code snippet does the following, when the form is submitted :
- checks whether email or password is enter or not.
- if any one of them is not entered, the focus sets to that particular field
- if both the fields are empty, and focus shifts to email field.
- in both 2 & 3, it throws error and ask user to enter them.
useContext :
Description :
Some times application needs a global data to be used across the application. It is really hard to pass down the global data to child components. Consider the following architecture A -> B -> C -> D where ‘A’ is parent component and ‘D’ is child component. Now if ‘D’ component wants some thing in common data like theming, active sessions / active tokens, or app content if thats been externalised, then passing from A -> D is so useless, if B, C doesn’t use them. Here where ‘Context’ comes into picture. Context is the hook where it provides the common data where ever necessary.
Custom Hooks :
1. we can create a wide variety of custom hooks using the react hooks.
2. custom hooks must start with the word ‘use’
3. these custom hooks are used for separating the logics from the parent / child components
Remember, in above useEffect example we created a component, where it updates the title of the page. Now let’s make it as a separate custom hook and use it when ever there is a page navigation.
Final notes
Apart from these there are other hooks which are used least,
- useCallback
- useMemo
- useImperativeHandle
- useLayoutEffect
- useDebugValue
Last but not least :
Hooks cannot be used outside a React Functional Component.
for code examples, please refer to my Github repo : Link here .