React Hooks allow functional components to manage state and life cycle events without needing to convert them into class components.
What are React Hooks?
Key takeaways:
React Hooks eliminate the need for class components by allowing you to manage state directly in functional components with Hooks like,
useState.The
useEffectHook helps manage side effects like data fetching, and DOM updates straightforwardly.Hooks like
useContextmake it easier to manage the global state across components without prop drilling. When combined with Redux or custom Hooks, they further streamline state sharing in complex apps.Hooks like
useRefgive direct access to DOM elements, offering better control over forms, animations, or other elements, avoiding unnecessary rerenders by maintaining a stable reference.
React is a JavaScript library for designing a web application’s user interface. It uses a component-like structure, where a web page is split into multiple components. Hooks were introduced in React version 16.8. With the help of these Hooks, we can reuse stateful logic and manage a component’s life cycle.
Rules to remember in React Hooks
There are some important rules to remember when using Hooks in React:
You should call Hooks only at the top level of the component, meaning they should not be called inside loops, conditions, or nested functions.
You should call Hooks only in React functional components or within custom Hooks. Hooks won’t work in class components or regular JavaScript functions outside the React environment.
Types of Hooks
Let’s look at some of the key hooks available to us in React.
1. The useState Hook
The useState Hook provides state management for functional components. It returns a state variable and a function to update that state. It is used to manage the local state of the component. The syntax to define it is as follows:
const [state, setState] = useState(initialValue);
Explore the
useStateHook by implementing it in a real world use case in this project: Build a Task Manager Using React.
Let’s look at a simple example of a counter demonstrating how to manage the state using the useState Hook:
Code explanation
Line 1: We import the
useStatehook from React.Line 4: We initialize the state variable price to
0and with the functionsetPriceto update it.Line 6: We define a function to increase the
priceby1when called.Line 10: We display the current value of the
pricestate.Line 11: When the button is clicked, we call the
increasePricefunction to update the state.
2. The useEffect Hook
The useEffect Hook manages side effects, like data fetching and setting up event listeners, in functional components. The syntax to define it is as follows:
useEffect(() => {// Side effect logic}, [dependencies]);
Let’s look at a simple example of how to fetch data from an API when the component mounts using the useEffect Hook:
Code explanation
Line 1: We import the
useStateanduseEffectHooks from React.Line 4: We initialize a local state,
posts, as an empty array.Lines 6–10: We define the
useEffectHook so that is executes after the component mounts.Line 7: We use the
fetchAPI to fetch posts from an API.Line 8: We convert the API response to JSON.
Line 9: We update the
postsstate with the fetched posts.
Lines 16–18: We render the title of each post inside a list element.
Practice using the
useEffectHook in a component with this project: Build an Image Sharing App with MERN Stack.
3. The useContext Hook
The useContext hook provides access to a shared state across components without prop drilling. The syntax to define it is as follows:
const value = useContext(Context);
Let’s look at a simple example that demonstrates how to share user data between components using the useContext Hook:
In this example, UserContext is created in the CreateContext.js file to act as a shared data source, provided through UserProvider in the UserProvider.js file (where the user state is initialized and passed to child components), enabling DisplayUser to access and display the user’s name directly from the context.
When you run the app, the output displays, User: John Doe. This confirms that the user state provided by the context ("John Doe") has been successfully retrieved by the DisplayUser component using useContext.
Code explanation
In the
CreateContext.jsfile, we usecreateContextto create a new context object,UserContext. We then export the context for use in other components.In the
UserProvider.jsfile, we do the following:Line 2: We import the
UserContext.Line 5: We initialize the
userstate.Line 8: We provide the
userstate to child components.Line 9: We render the children wrapped by the provider.
In the
DisplayUser.jsfile, we do the following:Line 1: We import the
useContextHook from React.Line 5: We access the
uservalue from context using theuseContextHook by passing itUserContextLine 7: We display the user’s name.
In the
App.jsfile, we do the following:Lines 2–3: We import the
UserProvidercontext andDisplayUsercomponent.Lines 6–8: We wrap the entire app to provide access to the context.
Line 7: We display the user value using the
DisplayUsercomponent.
Learn more the
useContexthook, by trying this project: Markdown Editor Application in React Using Context APIs and Hooks.
4. The useRef Hook
The useRef Hook allows you to interact with DOM elements directly without causing rerenders.
const ref = useRef(initialValue);
Let’s look at a simple example that shows how to focus an input field using the useRef Hook:
In the example above, the input field (textbox) is empty before clicking the button, and there is no focus on it. The cursor will not appear inside the input field initially.
After clicking the button, the handleClick function will run, causing the input field to receive focus. You’ll see the cursor blinking inside the textbox, meaning the input field is now active and ready for typing.
Code explanation
Line 1: We import the
useRefhook from React.Line 4: We create a reference to the input element.
Line 7: We focus on the input field when the function is called.
Line 13: We attach the reference to the input element.
Line 18: We trigger the
focusInputfunction on a button click.
Note: Besides the hooks discussed above, there are other Hooks like,
useMemo,useCallback,useReducer. Moreover, we can create custom hooks using JavaScript functions according to the requirements of our application.
Advantages of using React Hooks
There are many advantages of using Hooks in our React application, some of which are listed below.
Simple code structure: With Hooks, we avoid using classes that reduce the amount of boilerplate code we include in our application.
Easier state management: By using Hooks, we can easily manipulate the state variable by using JavaScript functions.
Improved performance: Hooks like
userMemoanduserCallbackprevent unnecessary rerendering of components and hence improve the overall application performance.Better application testing: As Hooks are individual logic units, we can use them independently while testing components without worrying about other components being affected.
Continue learning React Hooks
Explore these projects for hands-on practice with React hooks to deepen your understanding of how Hooks work and gain practical experience.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What is the purpose of React Hooks?
What is a custom Hook in React?
What is the purpose of useRef and how is it different from state?
What are the basic Hooks in React?
Free Resources