React JS Interview Questions
useRef() v/s useState()
When to use
useRef()
instead ofuseState()
A rule of thumb is to use
useState
when you need to re-render the component when the state changes anduseRef
when you don't need to re-render the component when the state changes.
Here are some examples of when to useuseRef
instead ofuseState
:
- When you need to store a value that does not trigger a re-render when it is updated.
- When you need to store a value that is not used in the render method.
- When you need to store a value that persists for the lifetime of the component.
What is the difference between useState and useEffect?
useState is a hook used to manage state in functional components, while useEffect is a hook used to manage side effects (like fetching data, setting up event listeners, or updating the DOM) in functional components.
In simple words,
useState
allows our functional components which used to be stateless become stateful. AnduseEffect
allows our functional components leverage the component lifecycle hooks which were, in the past, only supported for class components.The
useEffect
hook allows us to respond to changes in the component lifecycle. The component lifecycle refers to a set of events that occur from the time a component is mounted to the DOM until it is removed.useEffect
is most commonly used to execute code when the component is initially rendered, when it is updated, and when it is unmounted.