ReactJS Interview Prep: What are Hooks, useState and useEffect
2 min readJun 18, 2024
What are hooks?
- Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class
- Hooks are for functional components
- Hooks are functions that let you “hook into” React state and lifecycle features from function components
useState
useState
is a hook.- We call it inside a function component to add some local state to it. React will preserve this state between re-renders.
useState
returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar tothis.setState
in a class, except it doesn’t merge the old and new state together.- The only argument to
useState
is the initial state. In the example above, it is0
because our counter starts from zero. Note that unlikethis.state
, the state here doesn’t have to be an object — although it can be if you want. The initial state argument is only used during the first render.
mport React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return…