React Hooks
Oluwapelumi Famakinde
Full Stack Developer | Bachelor's in Computer Software Engineering
React Hooks are functions that allow you to use state and other React features in function components. They were introduced in React 16.8 to provide state management and lifecycle features in functional components, which were previously only available in class components.
Here are some commonly used React Hooks:
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count +1)}>Increment
</button>
</div>
);
}
import React, { useState, useEffect } from 'react'; function Example() {
const [data, setData] = useState([]);
useEffect(() => {
// Perform data fetching here
fetchData()
.then((response) => setData(response.data));
}, []); // Empty array means this effect runs once after the initial render
}
领英推荐
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
function Example() {
const theme = useContext(ThemeContext);
return (
<div style={{ background: theme.background, color: theme.text }}>
This component uses the theme from context.
</div>
);
}
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:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() =>
dispatch({ type: 'increment'})}>
Increment
</button>
<button onClick={() =>
dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
import React, { useRef } from 'react';
function Example() {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}
These are some of the core React Hooks, but there are many others available for various use cases. React Hooks have greatly simplified state management and side effects in React functional components, making it easier to write and maintain clean and concise code.