React Hooks Interview Questions

React Hooks Interview Questions

What are React Hooks?

React Hooks are functions that allow you to “hook into” React state and lifecycle features from function components. They were introduced in React 16.8 to allow using state and other React features without writing a class.

What are the Rules of Hooks?

  1. Only call Hooks at the top level of your function component
  2. Only call Hooks from React function components or custom Hooks

What is the useState Hook?

The useState Hook lets you add state to function components. Here’s an example:

function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

What is the useEffect Hook?

The useEffect Hook lets you perform side effects in function components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes.

useEffect(() => {
// Side effect code here
return () => {
// Cleanup code here
};
}, [dependencies]);

What is the useContext Hook?

The useContext Hook lets you subscribe to React context without nesting. It accepts a context object and returns the current context value.

const value = useContext(MyContext);

What are Custom Hooks?

Custom Hooks are JavaScript functions whose names start with “use” and may call other Hooks. They let you extract component logic into reusable functions.

function useWindowSize() {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
useEffect(() => {
const handleResize = () => {
setSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return size;
}

Share & Connect