The Heart of React: Exploring the Core Hooks for Seamless Development

Manish Singh
3 min readFeb 22, 2024

--

Why did the React component go fishing? It wanted to hook some state!

In today’s React development landscape, hooks have transformed how we approach writing functional components. They offer a straightforward method to incorporate stateful logic and side effects into functional components, eliminating the need to convert them into class components. In this article, we’ll delve into key React hooks, understand their appropriate usage, and master their effective implementation.

REACT

1. useState Hook:

When to use: Use the useState hook when you need to manage state within a functional component. It's ideal for creating and updating local component state.

Example Usage:

import React, { useState } from 'react';

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

const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};

export default Counter;

2. useEffect Hook:

When to use: Use the useEffect hook for handling side effects in functional components, such as data fetching, subscriptions, or DOM manipulation after rendering.

Example Usage:

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

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

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

return (
<div>
{data ? (
<p>Data: {JSON.stringify(data)}</p>
) : (
<p>Loading...</p>
)}
</div>
);
};

export default DataFetcher;

3. useContext Hook:

When to use: Use the useContext hook when you need to access shared values from React context within functional components. It's useful for avoiding prop drilling and accessing global data.

Example Usage:

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

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

return <button style={{ background: theme.background, color: theme.foreground }}>Themed Button</button>;
};

export default ThemedButton;

4. useRef:

  • When to use: useRef is perfect for accessing DOM elements directly or for storing mutable values that persist between renders.
  • Example Usage: Suppose you have a form with an input field and you want to focus on that input field when the component mounts. You can achieve this using useRef:
import React, { useRef, useEffect } from 'react';

function MyForm() {
const inputRef = useRef(null);

useEffect(() => {
inputRef.current.focus();
}, []);

return (
<form>
<label>
Enter your name:
<input type="text" ref={inputRef} />
</label>
<button type="submit">Submit</button>
</form>
);
}

export default MyForm;

Why did the React component bring a mirror to the party? To ‘useRef’ lect on its own reflection!

5. useCallback:

  • When to use: useCallback is valuable when you need to memoize callbacks, especially in scenarios where child components rely on props that are functions, to prevent unnecessary re-renders.
  • Example Usage: Let’s say you have a child component that receives a callback function as a prop, and you want to prevent it from being recreated on every render:
import React, { useCallback } from 'react';

function ChildComponent({ onClick }) {
return <button onClick={onClick}>Click me!</button>;
}

function ParentComponent() {
const handleClick = useCallback(() => {
console.log('Button clicked!');
}, []);

return <ChildComponent onClick={handleClick} />;
}

export default ParentComponent;

Why did the React function take a break? It needed to ‘useCallback’ its energy for the next render!

Conclusion:-

In summary, React hooks have revolutionized how we build React apps, making it easier to handle state, effects, and context in functional components. By learning key hooks like useState, useEffect, useRef, useCallback, and useContext, developers can create cleaner, more efficient components.

So, dive into using these hooks in your React projects today and see how they can supercharge your development workflow!

Thank you for diving into the world of React hooks with us! Now, go forth and build amazing things with the power of functional components. Happy coding!
Feel Free to connect with me on LinkedIn .
For More Blogs …
SQL VS NoSQL …… CRUD SQL………

Thank you ..

--

--

Manish Singh

Passionate about tech innovation & MERN stack. Join me as we explore code, creativity, & the endless possibilities of technology together! #MERN