”;
Until React 16.8, function components are simply stateless component. To add state to a component, we need to convert the function component into class based component. Also, function component does not have option to manipulate lifecycle events of a component. To enable state and lifecycle events in the function component, React introduced a new concept called Hooks.
Hooks are plain JavaScript functions having access to state and lifecycle events of the component in which it is used / applied. In general, hooks starts with use keyword. React comes with a few built-in hooks and allows the creation of custom hooks as well.
Built-in hooks
Let us know the list of hooks available in React and its basic usage.
-
useState − Used to manipulate state of the component.
-
useReducer − Advanced version of useState hooks with reducer concept.
-
useEffect − Used to hook into lifecycle of the component.
-
useLayoutEffect − Similar to useEffect, but gets triggered synchronously after all DOM mutation or just before the DOM is going to painted on the screen.
-
useContext − Provides access to the context provider inside a component.
-
useMemo − Used to return a memoized version of a variable / function, which only changes based on supplied predefined set of dependencies. This will reduce the number of recomputation of expensive calculation and improves the performance of the application.
-
useCallback − returns a memoized version of a callback function, which only changes based on supplied predefined set of dependencies.
-
useRef − Provides access to a raw DOM node based on React ref object.
-
useImperativeHandle − Used to expose ref based value in the child component to parent component.
-
useDeferredValue − Used to defer a value similar to debouncing or throttling to defer updates.
-
useDebug − Used to display label for custom hooks in React DevTools.
-
useTransition − Used to identify the pending state of the transition.
-
useId − Used to create unique ID for an element in the application.
Applying hooks
Let us learn how to use a hook in a function component by creating an application.
Create a React application using create-react-app and start the application using below command
create-react-app myapp cd myapp npm start
Next, let us create a new Function component HelloWorld (src/components/HelloWorld.js), which render an input element and renders a greeting message based on the data entered into the input element by the user.
import { useState } from ''react''; export default function HelloWorld() { const [name, setName] = useState("World") return ( <div style={{ textAlign: "center", padding: "5px" }}> <input id="name" name="name" value={name} onChange={(e) => setName(e.target.value)} /> <div>Hello {name}</div> </div> ) }
Here,
-
useState is a hook, which receives an initial value and returns a state and a function to update the state. it receives World as initial value and returns an array with two items, a) initial value of the state (name) and b) a function to update state (setName). The syntax used is array destruction syntax to get and set the array values into name and setName variables.
-
input is a react input element with an onChange event attached to it. onchange event get the user”s updated values through event.target.value and set it into the current state using setName function.
-
Whenever user updates the input, onchange event fires and update the state, which inturn fires the render function of the component.
Next, let us apply our component in our application (App.js) as shown below −
import ''./App.css''; import HelloWorld from ''./components/HelloWorld''; function App() { return ( <HelloWorld /> ); } export default App;
Finally, open the browser and check the results by changing the input value. The message gets updated whenever the input changes as shown below −
Advantages of Hooks
Function component have many advantages over class based component when used along with Hooks. They are as follows −
-
Hooks are easy to understand and quick to start coding.
-
The complexity of the application can be kept minimum in a large application. In class based component, the complexity (state management and handling lifecycle events) grows as the project grows.
-
this in class (component) is hard to understand for a beginner in JavaScript programming. Since Function component and hooks don”t depends on this, developers can quickly start coding in React without steep learning curve.
-
Stateful logic can be reused easily between components.
-
Function component can be used along with class based component, which makes it easily adoptable in the existing project of any size.
-
Function component can be written is few lines of code compared to class based components.
Disadvantages of Hooks
Hooks are alternative methodology to create components and it has its own disadvantages as well. They are as follows −
-
Hooks should be called only at top level and should be avoided inside a condition, loop or nested function.
-
Hooks are specialized features that they may not be best fit for certain situation and we may have to restore to class based component.
-
React handles the internals of hooks without exposing the core for optimization, which makes it less flexible and not suitable for certain scenarios.
Summary
Hooks are relatively new way of creating components. Large collection of project are still using class based component. Converting the component in those projects from class based to function based is not practically possible and we have to live with it. Instead, we can convert the application in the phased manner.
”;