5 Fundamental React Hooks Every Developer Should Know
React Hooks are an essential part of modern React development. If you're preparing for a job interview, it's crucial to understand at least the basic hooks. Here are five fundamental React Hooks you should know.
1. useState
The useState
hook is used to manage state in functional components. It lets you add state variables to your component without converting it into a class.
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>
);
}
2. useEffect
The useEffect
hook allows you to perform side effects in your components, such as fetching data, directly manipulating the DOM, or setting up subscriptions. It runs after the component renders.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
3. useContext
The useContext
hook lets you subscribe to React context without introducing nesting. It's useful for passing data through the component tree without having to pass props down manually at every level.
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>I am styled by theme context!</button>;
}
4. useRef
The useRef
hook allows you to create a mutable object that persists across renders. It’s often used to reference a DOM element or store a value that doesn’t trigger a re-render when updated.
import React, { useRef } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<div>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</div>
);
}
5. useImperativeHandle
The useImperativeHandle
hook customizes the instance value that is exposed to parent components when using ref
. It’s useful for defining functions that the parent component can call on the child component.
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
const FancyInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
});
function App() {
const inputRef = useRef();
return (
<div>
<FancyInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</div>
);
}