DEV Community

Jayant
Jayant

Posted on

Reconciliation & ForwardRef In React

Reconciliaiton in React

What

It is a mechanism to efficently update the UI by calculating the differences between Virtual DOM trees and applying only the necessary changes to the actual DOM.

The Virtual DOM trees are compared using a diffing algorithm.

  • For Components, the diffing algorithm compares the props and the state of the component. Basically it checks for the arguments passed to the component.
  • For Children, it checks if keys are same or not.
  • For Elements, it checks for the element type if it is changed.

Why

Updating actual DOM is expensive. So, it is better to update only the necessary changes.

Example: Suppose we have a simple Component that shows count value

function App() { const [count, setCount] = React.useState(0); return ( <div> <p>Count: {count}</p>  <button onClick={() => setCount(count + 1)}>Increment</button>  </div>  ); } 
Enter fullscreen mode Exit fullscreen mode

What happen state changes?

  • React create a new Virtaul DOM tree with the updated count value.
  • Compares it with the previous Virtual DOM tree.
  • Updates only the <p> tag.

Forward Ref

What

Forward Ref is a Higher order Component that allows a component to forward a ref that is received from parent to one of its childeren.

  • It is used to access the DOM element of a child component.

Why

React encapsulates components, preventing direct access to their internal DOM elements or instances. Sometimes we need to access the DOM element of a child component. For example, we want to focus on a particular element when a button is clicked or gets the value of an input field. So for that reason we use forwardRef.

It allows the parent to directly interact with the child’s DOM node or component instance.

How

Steps to use forwardRef

  • Create a ref object using useRef or createRef.
  • Pass the ref object to the Child Component.
  • Wrap the child component with forwardRef HOC.
  • The forwardRef HOC takes a render function as an argument and render function 1st argument is the props object & 2nd argument is ref.
  • If we don't use forwardRef HOC, we can't access the ref object.
const MyButton = React.forwardRef((props,ref)=>{ return <button ref={ref}> {props.children} </button> }) const buttonRef = React.useRef(null); <MyButton ref={buttonRef}> Pls Click </MyButton> 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)