Understanding React Hooks and When to Use Them

Nitin Rachabathuni
2 min readMay 2, 2024

--

Introduction

  • Brief introduction to React, a popular JavaScript library for building user interfaces.
  • Mention the introduction of Hooks in React 16.8 as a significant update.
  • Explain the purpose of Hooks: to enable state and other React features in functional components.

What are Hooks?

  • Define Hooks as functions that let you “hook into” React state and lifecycle features from function components.
  • Mention some of the most commonly used Hooks: useState, useEffect, and useContext.

When to Use Hooks

  • Discuss when to use Hooks: converting a class component to a function component, reusing stateful logic between components, and managing local component state.

Common Hooks and Their Uses

  1. useState
  • Purpose: To add state to functional components.
  • Example
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>
);
}
  • Explanation: Demonstrates initializing state in a function component and updating it with a button click.

2. useEffect

  • Purpose: To perform side effects in function components (similar to componentDidMount, componentDidUpdate, and componentWillUnmount in class components).
  • Example:
import React, { useState, useEffect } from 'react';

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

useEffect(() => {
document.title = `You clicked ${count} times`;
});

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
  • Explanation: Shows how to use useEffect to handle side effects, updating the document's title whenever the count changes.
  1. useContext
  • Purpose: To subscribe to React context without introducing nesting.
  • Example:
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');

function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme === 'dark' ? 'black' : 'white' }}>
I am styled by theme context!
</button>
);
}

Thank you for reading my article! For more updates and useful information, feel free to connect with me on LinkedIn and follow me on Twitter. I look forward to engaging with more like-minded professionals and sharing valuable insights.

--

--

Nitin Rachabathuni
Nitin Rachabathuni

Written by Nitin Rachabathuni

Seeking freelance opportunities | React.js, Next.js, Vue.js, Angular, Node.js, Commercetools, Merchant Center, Frontastic, Azure, AWS | +91-9642222836

No responses yet