React Hooks allow functional components to manage state and life cycle events without needing to convert them into class components.
CARVIEW |
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
useEffect
Hook helps manage side effects like data fetching, and DOM updates straightforwardly.Hooks like
useContext
make 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
useRef
give 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
useState
Hook 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
useState
hook from React.Line 4: We initialize the state variable price to
0
and with the functionsetPrice
to update it.Line 6: We define a function to increase the
price
by1
when called.Line 10: We display the current value of the
price
state.Line 11: When the button is clicked, we call the
increasePrice
function 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
useState
anduseEffect
Hooks from React.Line 4: We initialize a local state,
posts
, as an empty array.Lines 6–10: We define the
useEffect
Hook so that is executes after the component mounts.Line 7: We use the
fetch
API to fetch posts from an API.Line 8: We convert the API response to JSON.
Line 9: We update the
posts
state with the fetched posts.
Lines 16–18: We render the title of each post inside a list element.
Practice using the
useEffect
Hook 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.js
file, we usecreateContext
to create a new context object,UserContext
. We then export the context for use in other components.In the
UserProvider.js
file, we do the following:Line 2: We import the
UserContext
.Line 5: We initialize the
user
state.Line 8: We provide the
user
state to child components.Line 9: We render the children wrapped by the provider.
In the
DisplayUser.js
file, we do the following:Line 1: We import the
useContext
Hook from React.Line 5: We access the
user
value from context using theuseContext
Hook by passing itUserContext
Line 7: We display the user’s name.
In the
App.js
file, we do the following:Lines 2–3: We import the
UserProvider
context andDisplayUser
component.Lines 6–8: We wrap the entire app to provide access to the context.
Line 7: We display the user value using the
DisplayUser
component.
Learn more the
useContext
hook, 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
useRef
hook 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
focusInput
function 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
userMemo
anduserCallback
prevent 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?
A custom Hook is a reusable function that encapsulates logic using existing Hooks. It can be shared across components for consistency and modular code.
What is the purpose of useRef and how is it different from state?
The useRef Hook stores a reference to a DOM element or mutable value that persists across renders. Unlike the state, it does not trigger a rerender when updated.
What are the basic Hooks in React?
useState
: Manages state in functional components.
useEffect
: Handles side effects, such as data fetching or DOM updates.
useContext
: Provides access to a shared state using React’s Context API.
useRef
: Allows interaction with DOM elements or persistent values without triggering rerenders.
useReducer
: Manages complex state logic with actions and reducers, similar to Redux.
Relevant Answers
Explore Courses
Free Resources