What are React hooks?
Answer
React hooks are functions that allow developers to use state and other React features in functional components. They were introduced in React 16.8 and have since become a popular way to manage state and side effects in React applications. There are two types of hooks: state hooks and effect hooks.
State hooks, such as useState, allow developers to add state to functional components. They work by returning an array with two elements: the current state value and a function to update the state value. For example, the following code uses the useState hook to add a counter to a functional component:
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>
);
}
Effect hooks, such as useEffect, allow developers to perform side effects in functional components. They work by running a function after every render of the component. This can be useful for fetching data, setting up subscriptions, or updating the DOM. For example, the following code uses the useEffect hook to fetch data from an API:
import React, { useState, useEffect } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => setUsers(data));
}, []);
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
In summary, React hooks are functions that allow developers to use state and other React features in functional components. They provide a simpler and more concise way to manage state and side effects in React applications.
Related React job interview questions
What are package managers in React?
React JuniorWhat three dots mean in React code?
React JuniorWhat is uncontrolled component in React?
React JuniorWhat is a controlled component in React?
React JuniorHow is state different than props in React?
React Junior