In React, both `createRef` and `useRef` are used to create references to DOM elements or class components, but they serve different purposes and are used in different contexts. Understanding these differences is crucial for effective component design and state management in React applications.
`createRef` is a method available in class components. It allows you to create a reference that can be attached to a React element. When the component mounts, the reference will point to the corresponding DOM node or class component instance.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myInputRef = React.createRef();
}
focusInput = () => {
this.myInputRef.current.focus();
};
render() {
return (
);
}
}
In this example, `createRef` is used to create a reference to an input element. The `focusInput` method can be called to focus the input when the button is clicked.
`useRef` is a Hook that can be used in functional components. It serves a similar purpose as `createRef`, but it is designed to work with the functional component lifecycle. One of the key differences is that `useRef` returns a mutable object whose `.current` property can be changed without causing a re-render of the component.
import React, { useRef } from 'react';
const MyFunctionalComponent = () => {
const myInputRef = useRef(null);
const focusInput = () => {
myInputRef.current.focus();
};
return (
);
};
In this functional component example, `useRef` is used to create a reference to an input element. The `focusInput` function behaves similarly to the class component example, allowing the input to be focused when the button is clicked.
| Feature | createRef | useRef |
|---|---|---|
| Component Type | Class Components | Functional Components |
| Re-rendering | New ref on each render | Stable ref across renders |
| Mutable Object | No | Yes |