Conquer the React hooks
The Things you need to know about React hooks that can help you to conquer the React Hooks concept.

I am a Software developer by profession and opensource contributor by passion.
Every single time you go out to the internet and search for react hooks but you can't understand react hooks efficiently so my friend this blog is for you which can help you to conquer the react hooks concept š.
So enjoy this blog from which you gather information about react hooks.
Here are some basic stuff about React Hooks
React Hooks are a feature introduced in React version 16.8. They allow you to use state and other React features in functional components without the need for class components. This simplifies the syntax and structure of React components.
You see that currently, all the people are using functional components so you need state management that's why you need to learn about React hooks. React Hooks also provide a way to share stateful logic between components, which can further simplify your code and reduce duplication.
Basic React Hooks
Here are some basic and commonly used React hooks.
- useState : This hook allows you to use state in functional components. It takes an initial value as an argument and returns an array with two elements: the current state and a function to update the state. Here's an example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
⢠In this example, we use the useState hook to initialize a state variable called count 0. We also define a function called handleClick that updates the count variable using the setCount function. Finally, we render the count variable and a button that calls the handleClick function when clicked.
useEffect : This hook allow you to perform side effects in your components. It takes a function as its first argument and an optional array of dependencies as its second argument. Here are some examples :
- Example one :
import React, { useState, useEffect } from 'react';
function Data() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
{data.map(item => (
<div key={item.id}>
<h3>{item.title}</h3>
<p>{item.body}</p>
</div>
))}
</div>
);
}
export default Data;
⢠In this example, the useEffect hook is used to fetch data from an API and set it as the state of the component. The second argument of useEffect is an empty array, which means that the effect will only be run once when the component is mounted. In this example, we don't pass a dependency array.
Example two :
import React, { useEffect } from 'react'; function Title({ title }) { useEffect(() => { document.title = title; }, [title]); return null; } export default Title;⢠In this example, the
useEffecthook is used to set the document title based on thetitleprop. The effect is run every time thetitleprop changes. The component returnsnullbecause it doesn't need to render anything. You see that we are passing the title as a dependency array.
- useContext : This hook allows you to use context in functional components. It takes a context object as its argument and returns the current value of the context. With the help of this hook, we handle the prop drilling. Here's an example:
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemeToggle() {
const theme = useContext(ThemeContext);
return (
<button
style={{ backgroundColor: theme === 'dark' ? '#333' : '#fff', color: theme === 'dark' ? '#fff' : '#333' }}
onClick={() => {
theme === 'dark' ? setTheme('light') : setTheme('dark');
}}
>
Toggle theme
</button>
);
}
⢠In this example, we create a context object called ThemeContext with a default value of light. We also create a component called ThemeToggle that uses the useContext hook to get the current value of the ThemeContext context. Finally, we render a button that toggles the theme when clicked.
Advanced React Hooks
You see that basic React hooks which used commonly. Now we see some advanced React hooks.
useReducer : The
useReducerhook is an alternative touseStatethat allows you to manage complex state logic in your application. It takes a reducer function and an initial state as arguments and returns the current state and a dispatch function to update the state. Here's an example :import React, { useReducer } from 'react'; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); } } function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <> Count: {state.count} <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> </> ); }⢠This code is an example of using the
useReducerhook in a React component to manage state. Thereducerfunction takes two arguments: the current state and an action object that describes how to update the state. In this case, the action object has atypeproperty that can be either "increment" or "decrement", and thereducerfunction returns a new state object that either increments or decrements thecountproperty of the previous state.⢠In the
Countercomponent, theuseReducerhook is used to initialize thestateobject with acountproperty set to 0, and to get thedispatchfunction that is used to update the state by dispatching actions to the reducer. TheCountis displayed using thestate.countvalue, and theonClickhandlers of the+and-buttons call thedispatchfunction with the corresponding action type to update the state.⢠Overall, this code demonstrates how the
useReducerhook can simplify state management in a React component by encapsulating the logic for updating state in a separate function.useCallback : The
useCallbackhook is used to memoize functions so that they do not have to be recreated every time a component re-renders. It takes a function and an array of dependencies as arguments and returns a memoized function. Here's an example :function MemoizedComponent({ onButtonClick }) { const handleClick = useCallback(() => { onButtonClick(); }, [onButtonClick]); return <button onClick={handleClick}>Click me</button>; }⢠In this example we defines a React functional component called
MemoizedComponentthat takes a prop calledonButtonClick. Within the component, theuseCallbackhook is used to memorize thehandleClickfunction so that it does not have to be recreated every time the component re-renders. ThehandleClickfunction simply calls theonButtonClickfunction that was passed in as a prop. Finally, thehandleClickfunction is passed as a callback to theonClickevent of a button element that is rendered by the component. When the button is clicked, thehandleClickfunction is called, which in turn calls theonButtonClickfunction.useMemo : The
useMemohook is used to memoize values so that they do not have to be recalculated every time a component re-renders. It takes a function and an array of dependencies as arguments and returns a memoized value. Here's an example :function ExpensiveCalculation({ value }) { const result = useMemo(() => { // Perform expensive calculation here return value * 2; }, [value]); return <div>Result: {result}</div>; }⢠This code defines a component called
ExpensiveCalculationthat takes a prop calledvalue. Within the component, theuseMemohook is used to perform an expensive calculation (multiplyingvalueby 2) and memoize the result so that it does not need to be recalculated every time the component re-renders. The memoized value is then returned and displayed in the component using theResult: {result}syntax.⢠In summary, this component optimizes performance by avoiding unnecessary recalculation of expensive calculations when the component re-renders.
useRef : The
useRefhook is used for accessing DOM nodes or storing mutable values in your application. It returns a mutable ref object that can be used to store and update values. The value of the ref persists between renders. Here's an example :function MyComponent() { const inputRef = useRef(null); function focusInput() { inputRef.current.focus(); } return ( <> <input type="text" ref={inputRef} /> <button onClick={focusInput}>Focus input</button> </> ); }⢠This code defines a functional component called
MyComponentthat renders an input element and a button. It uses theuseRefhook to create a reference to the input element, which is assigned to theinputRefconstant.⢠The
focusInputfunction is defined insideMyComponentand uses thecurrentproperty of theinputRefobject to access the actual DOM node of the input element and call itsfocus()method, which sets the focus to the input.⢠The button element has an
onClickevent handler that calls thefocusInputfunction when clicked, which triggers the focus of the input element.⢠In summary, this code creates a component that allows the user to focus on an input element by clicking a button using the
useRefhook to access the input element and itsfocus()method.
Conclusion
Using React Hooks can simplify your code and make it easier to reason about, as it encourages a more functional programming style. However, it's important to use them correctly and understand their limitations, as improper use can lead to unexpected behavior or performance issues. You should build customer hooks that can help you to build reusable functions that a React JS software developer can use to add special and unique functionality to the React applications.
