Mastering React.js: Essential Hooks You Need to Know

Shreyash chaurasia
3 min readJun 14, 2024

--

React.js has revolutionized the way we build user interfaces with its component-based architecture. One of the key features that makes React so powerful and flexible is its Hooks API. Hooks allow you to use state and other React features without writing a class. In this blog post, we’ll explore some of the most important hooks in React.js that every developer should know.

  1. useState

The useState hook is the most basic and commonly used hook. It allows you to add state to functional components. When you call useState, it returns an array with two elements: the current state value and a function to update it.

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}

2. useEffect

The useEffect hook lets you perform side effects in function components. It's similar to lifecycle methods in class components like componentDidMount, componentDidUpdate, and componentWillUnmount combined. You can use it for data fetching, subscriptions, or manually changing the DOM.

import React, { useState, useEffect } from 'react';

function DataFetcher() {
const [data, setData] = useState([]);

useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);

return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}

3. useContext

The useContext hook allows you to access the value of a context directly in your functional components. It's a more straightforward way to consume context compared to the traditional Context.Consumer component.

import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function ThemedButton() {
const theme = useContext(ThemeContext);

return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}

4. useReducer

The useReducer hook is often preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. It works similarly to Redux but is simpler and built into React.

import React, { useReducer } from 'react';

const initialState = { count: 0 };

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, initialState);

return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}

5. useMemo

The useMemo hook is used to memoize expensive calculations, improving performance. It only recomputes the memoized value when one of its dependencies changes.

import React, { useState, useMemo } from 'react';

function ExpensiveCalculation({ num }) {
const computeFactorial = (n) => {
console.log('Computing factorial...');
return n <= 0 ? 1 : n * computeFactorial(n - 1);
};

const factorial = useMemo(() => computeFactorial(num), [num]);

return <div>Factorial of {num} is {factorial}</div>;
}

6. useCallback

The useCallback hook returns a memoized callback function. It is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

import React, { useState, useCallback } from 'react';

function Parent() {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount(count + 1), [count]);

return (
<div>
<Child onClick={increment} />
<p>{count}</p>
</div>
);
}

const Child = React.memo(({ onClick }) => {
console.log('Child render');
return <button onClick={onClick}>Increment</button>;
});

Conclusion

React hooks are a powerful feature that can simplify your code and make it more readable. By understanding and utilizing these important hooks — useState, useEffect, useContext, useReducer, useMemo, and useCallback—you can write more efficient and effective React applications. Happy coding!

--

--

Shreyash chaurasia

👋 Hi, I'm Shreyash! I'm a Full Stack Developer currently mastering the MERN stack . With a passion for building scalable and efficient web applications.