Requirements
Here are some necessities needed to complete this project
Node version 14+ and NPM version 5.6+ installed
Command Line Interface (I will be using PowerShell)
Basic JavaScript Knowledge
Basic Reactjs knowledge
Basic Bash Scripts Knowledge
Strong Internet connection
Getting Started
React Hooks is a game-changer when it comes to writing code with React. They offer a simpler and more intuitive way to write React components than traditional React classes.
React hooks are reusable pieces of code, and react hooks are reusable code logic to perform repeated tasks.
This means you can invoke a function in another function and use its output. Now, let's define what react hooks are in a broader term:
What Are React Hooks
React Hooks are functions that allow developers to use React state and other React features without having to write a class component. Hooks are essential for writing modern React applications, allowing developers to keep the code simple and organized.
React Hooks makes it easier for developers to track the state of their components. By using Hooks, developers can track which components are changed and which are not. This allows developers to organise their code better and ensure all components are updated.
With React Hooks, we can use state and other React features in a functional component. It empowers devs to perform highly functional programming in React.
Standard in-built hooks
useState
To manage states. Returns a stateful value and an updater function to update it. Here is an example:
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
in the above code, The state starts as { count: 0 }, and we increment the count when the user clicks a button by calling setCount().
useEffect
Manage side effects like API calls, subscriptions, timers, and mutations. Here is an example
import { useEffect } from 'react';
function User({ name }) {
useEffect(() => {
document.title = name;
}, [name]);
return <h1>{name}</h1>;
}
The function passed to useEffect is a callback function. This will be called after the component renders. We can perform our side effects or multiple side effects in this function. The second argument is an array called the dependencies array. This array should include all the values our side effect relies upon. In our example above, since we are changing the title based on a value in the outer scope, name, we need to include that within the dependencies array. What this array will do is it will check and see if a value (in this case, name) has changed between renders. If so, it will execute our use effect function again. This makes sense because if the name changes, we want to display that changed name and therefore run our side effect again.
useContext
To return the current value for a context. Here is an example
import { useContext } from 'react';
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
//...
The useContext here returns the context value for the context you passed. To determine the context value, React searches the component tree and finds the closest context provider above for that particular context.
useReducer
A useState alternative to help with complex state management, Here is an example.
import { useReducer } from 'react';
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
Above, the reducer function specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return to the next state. the state and action can be of any type.
useCallback
It returns a memorized version of a callback to help a child component not re-render unnecessarily.
import { useCallback } from 'react';
export default function ProductPage({ productId, referrer, theme }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]);
The function value that you want to cache. It can take any argument and return any values. React will return (not call!) your function back to you during the initial render. On next renders, React will give you the same function again if the dependencies have not changed since the last render. Otherwise, it will give you the function you passed during the current render and store it in case it can be reused later. React will not call your function. The function is returned to you so you can decide when and whether to call it.
useMemo
It returns a memoized value that helps in performance optimizations.
import { useMemo } from 'react';
function TodoList({ todos, tab, theme }) {
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
// ...
}
You need to pass two things to useMemo:
A calculation function that takes no arguments, like () =>, and returns what you wanted to calculate.
A list of dependencies includes every value within your component used in your calculation.
On the initial render, the value you’ll get from useMemo will be the result of calling your calculation.
useRef
It returns a ref object with a .current property. The ref object is mutable. It is mainly used to access a child component imperatively.
import { useRef } from 'react';
function Stopwatch() {
const intervalRef = useRef(0);
// ...
the useRef returns a ref object with a single current property initially set to the initial value you provided.
On the next renders, useRef will return the same object. You can change its current property to store information and read it later. This might remind you of the state, but an important difference exists.
useLayoutEffect
It fires at the end of all DOM mutations. Using useEffect as much as possible over this one is best as the useLayoutEffect fires synchronously.
function Tooltip() {
const ref = useRef(null);
const [tooltipHeight, setTooltipHeight] = useState(0); // You don't know real height yet
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTooltipHeight(height); // Re-render now that you know the real height
}, []);
// ...use tooltipHeight in the rendering logic below...
}
The above code is explained below
Tooltip renders with the initial tooltipHeight = 0 (so the tooltip may be wrongly positioned).
React places it in the DOM and runs the code in useLayoutEffect.
Your useLayoutEffect measures the height of the tooltip content and triggers an immediate re-render.
Tooltip renders again with the real tooltipHeight (so the tooltip is correctly positioned).
React updates it in the DOM, and the browser displays the tooltip.
useDebugValue
Helps to display a label in React DevTools for custom hooks.
import { useDebugValue } from 'react';
function useOnlineStatus() {
// ...
useDebugValue(isOnline ? 'Online' : 'Offline');
// ...
}
This gives components calling useOnlineStatus a label like OnlineStatus: "Online" when you inspect them.
You can read more about these hooks in more detail here.
You should notice that each of these hook names starts with use. This is a standard practice to identify a hook in the React codebase quickly.
Conclusion
Finally, React Hooks can help increase the performance of an application. React Hooks are optimized for performance, so developers can rely on them to create high-performing applications.
Overall, React Hooks are a great way to simplify the code for React applications. They make it easier to reuse code, share logic across components, and ensure that components are updated. React Hooks are essential for creating modern React applications, and any developer who wants to get the most out of React should learn how to use them.