React.createRef vs React.useRef

Thursday, March 3, 20222 min read

What is a ref?

A ref is defined as any value that does not trigger a component re-render when it is changed. A ref can be created with React.useRef() hook or by the React.createRef() function.

React.createRef

The React.createRef() is a function that creates a new ref every time, it does not save its value between re-renders, instead creates a new instance of the ref for every re-render.

On class refs are created using React.createRef() and attached to React elements via the ref attribute, are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

1class MyComponent extends React.Component {
2 constructor(props) {
3 super(props);
4 this.myRef = React.createRef();
5 }
6 render() {
7 return <div ref={this.myRef} />;
8 }
9}

Accessing Refs

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

1const node = this.myRef.current;

The value of the ref differs depending on the type of the node:

React.useRef

The React.useRef() is a hook that uses the same ref throughout, it saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render.

You can, however, use the ref attribute inside a function component as long as you refer to a DOM element.

1function CustomTextInput(props) {
2 const textInput = useRef(null);
3
4 function handleClick() {
5 textInput.current.focus();
6 }
7
8 return (
9 <div>
10 <input type="text" ref={textInput} />
11 <input
12 type="button"
13 value="Focus the text input"
14 onClick={handleClick}
15 />
16 </div>
17 );
18}

Conclusion

The difference is that React.createRef() will always create a new ref in a class-based component, React.useRef() takes care of returning the same ref each time as on the initial rendering.


Thursday, June 27, 2024

Introduction of the useBem hook for React

Discover the power of the useBem hook to streamline your CSS class management, learn how to apply the BEM methodology to ensure consistent, readable, and maintainable styling across your front-end projects.


Wednesday, October 4, 2023

SOLID Principles in React

Let's explore how the SOLID principles can be applied to React components using TypeScript, functions, hooks, and interfaces.