Table of Contents
ToggleUseref vs Usestate: Definition and Functions
As the name suggests, useRef works with references. UseRef is a React hook that allows you to reference a value that is not needed for rendering. Its main purpose is to provide DOM access to work with child elements.
The useRef hook can be used to store a variable value that does not cause re-rendering during an update. This would be useful for directly accessing a DOM element. UseRef is used to avoid re-renders and avoid infinite loops.
This hook is needed to keep track of previous state values. This is because we can persist the useRef value between renders.
Below you can see an example of using useRef in code.
To compare useRef vs useState, you need to understand what useState is. Coding can seem as complicated and confusing as removing that nasty Avast from your PC. Let’s start to get new knowledge!
UseState is a React hook that allows you to add a state variable to your component.
UseState() is used to manage the component state. This function returns a getter/setter pair – the initial state value and a function to update this value. The function has the following signature: const [value, setValue] = useState(defaultValue).
UseState returns an array containing exactly two values:
- The current state. During the first render, this will match the initialState you passed.
- The set function, which allows you to update the state to a different value and force a re-render.
UseState does NOT initialize the state during every render. It only initializes the state for its first render.
UseState is used for:
– state management, including passing data as props to other components;
– conditional rendering – rendering of certain data, depending on what is stored in the state;
– to switch the state (true/false);
– as a counter for something;
– storing data received from the server.
Here is an example of using useState:
UseState vs useRef: Main Differences
The main difference between useState and useRef is this: useState causes a re-render, useRef does not.
What they have in common is that both useState and useRef can remember their data across re-renders. So if your variable is what decides the view layer render, use useState. Otherwise, use useRef.
When is it best to use useRef?
– if you want to persist values without re-rendering.
– if you want direct access to DOM elements.
When is it best to use useState?
– if you want stateful logic that affects rendering.
– if you want to manage dynamic values that affect the UI.