React Hooks allow functional components to manage state and life cycle events without needing to convert them into class components.
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.
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.
Let’s look at some of the key hooks available to us in React.
useState
HookThe 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:
Line 1: We import the useState
hook from React.
Line 4: We initialize the state variable price to 0
and with the function setPrice
to update it.
Line 6: We define a function to increase the price
by 1
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.
useEffect
HookThe 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:
Line 1: We import the useState
and useEffect
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.
useContext
HookThe 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
.
In the CreateContext.js
file, we use createContext
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 the useContext
Hook by passing it UserContext
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 and DisplayUser
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.
useRef
HookThe 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.
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.
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
and userCallback
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.
Explore these projects for hands-on practice with React hooks to deepen your understanding of how Hooks work and gain practical experience.
Haven’t found what you were looking for? Contact Us
Free Resources