Understanding React Hooks and When to Use Them
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
, anduseContext
.
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
- 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
, andcomponentWillUnmount
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.
- 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>
);
}