- Published on
Understanding React Hooks with Simple Examples
- Authors
- Name
- codewithininsight
- @
React Hooks are one of the most powerful features of React, allowing you to use state and lifecycle methods in functional components. In this blog, we’ll explore some of the most commonly used React Hooks with easy-to-understand examples.
What Are React Hooks?
React Hooks are functions that let you "hook into" React’s state and lifecycle features without writing a class. Hooks were introduced in React 16.8 and have since become the standard for creating React components.
Commonly Used React Hooks
Let’s explore the most popular React Hooks with simple examples:
1. useState
The useState
hook lets you add state to a functional component.
Example: Counter
import React, { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
)
}
export default Counter
Explanation:
useState(0)
initializes the state with0
.setCount
is a function to update the state.
2. useEffect
The useEffect
hook lets you perform side effects in your components, such as fetching data or updating the DOM.
Example: Fetch Data
import React, { useState, useEffect } from 'react'
function DataFetcher() {
const [data, setData] = useState(null)
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => response.json())
.then((data) => setData(data))
}, []) // Empty dependency array to run only once
return <div>{data ? <p>{data.title}</p> : <p>Loading...</p>}</div>
}
export default DataFetcher
Explanation:
- The
useEffect
hook runs the fetch logic when the component mounts. - The empty dependency array
[]
ensures it runs only once.
3. useContext
The useContext
hook allows you to consume context values in your components.
Example: Theme Context
import React, { createContext, useContext } from 'react'
const ThemeContext = createContext('light')
function ThemedComponent() {
const theme = useContext(ThemeContext)
return <p>The current theme is {theme}</p>
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedComponent />
</ThemeContext.Provider>
)
}
export default App
Explanation:
createContext
creates a Theme Context with a default value of"light"
.useContext
retrieves the current value of the context.
4. useRef
The useRef
hook lets you persist values across renders without causing re-renders.
Example: Focus Input
import React, { useRef } from 'react'
function FocusInput() {
const inputRef = useRef(null)
const handleFocus = () => {
inputRef.current.focus()
}
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleFocus}>Focus Input</button>
</div>
)
}
export default FocusInput
Explanation:
useRef
creates a reference to the input element.inputRef.current.focus()
focuses the input when the button is clicked.
5. useReducer
The useReducer
hook is an alternative to useState for managing complex state logic.
Example: Simple Counter with Reducer
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 (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
)
}
export default Counter
Explanation:
useReducer
uses a reducer function to manage state updates.dispatch
triggers actions to update the state.
Summary
React Hooks make functional components powerful and concise, allowing you to manage state, handle side effects, and much more. Start experimenting with Hooks in your projects to simplify your React codebase.
Key Hooks Recap:
useState
: Manage state.useEffect
: Handle side effects.useContext
: Consume context values.useRef
: Access DOM elements or persist values.useReducer
: Manage complex state logic.
For more advanced usage, check out the official React Hooks documentation.