React JS Interview Questions
useRef() v/s useState()
When to use
A rule of thumb is to use
useStatewhen you need to re-render the component when the state changes and
useRefwhen you don't need to re-render the component when the state changes.
Here are some examples of when to use
- 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,
useStateallows our functional components which used to be stateless become stateful. And
useEffectallows our functional components leverage the component lifecycle hooks which were, in the past, only supported for class components.
useEffecthook 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.
useEffectis most commonly used to execute code when the component is initially rendered, when it is updated, and when it is unmounted.