Can you explain the concept of hooks in React and how they differ from class components?

In React, hooks are a way to use state and other React features in functional components, rather than just in class components.

Hooks allow you to use features such as state, lifecycle methods, and context in functional components, which previously could only be used in class components. This can make your code more organized, easy to understand and also allows you to share stateful logic across multiple components.

Here are some examples of hooks:

  • useState: Allows you to add state to a functional component. It returns an array with two elements, the current state and a function to update it.
const [count, setCount] = useState(0);

useEffect: Allows you to run side-effects, such as fetching data, after the component has rendered. It has the same behavior as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

useEffect(() => { document.title = `You clicked ${count} times`; }, [count]);

useContext: Allows you to access the context without having to pass props down manually through multiple levels of components.

const theme = useContext(ThemeContext);

Class components are still supported in React, but using hooks can make your code more readable, less complex and also easier to test.

In summary, hooks are a way to use state and other features in functional components, giving developers more flexibility and code reusability. They provide the same features as class components but in a more organized and easy-to-understand way.