Deep understanding of Ref/Direct Manipulation in React-Native

Payal Maniyar
2 min readJan 17, 2019

I came across the Ref/Direct Manipulation in React-Native Doc. I was not aware of that so read it. But that doc info does not give me full satisfaction so decided to get deeper knowledge about that. Here sharing my knowledge with you guys…..

Let's first understand how any components display on screen…

To display any component in the screen you have to write code for that component in render() method.

Now what if want to add/change any component(call the render method)?

The answer is we have to change state or props, otherwise, the render() will not be called. Render method renders the whole component hierarchies even if there is a change in the only one component.

Is there any solution which does not render all the component hierarchies for one component change?

Yes. the solution is Direct Manipulation…..

What is Direct Manipulation?

It is sometimes necessary to make changes directly to a component without using state/props(or render whole hierarchies of components for a small change in one component). This process is called Direct Manipulation.

How Direct Manipulation Works?

It uses setNativeProps and Refs.

When to use setNativeProps and Refs?

Use setNativeProps when frequent re-rendering creates a performance bottleneck

Direct manipulation will not be a tool that you reach for frequently; you will typically only be using it for creating continuous animations to avoid the overhead of rendering the component hierarchy and reconciling many views. setNativeProps is imperative and stores state in the native layer (DOM, UIView, etc.) and not within your React components, which makes your code more difficult to reason about. Before you use it, try to solve your problem with setState and shouldComponentUpdate.

Let's understand with one example using setState and setNativeProps/Refs.

We have one TextInput which should be clear the text when clear button is clicked.

  1. How to achieve using setState?

Here is the code snippet which uses setState.

Here each time we change the text or click clear button, render method is called which rerender the whole component even if there is a change for the component.

2. How to achieve using setNativeProps and Refs?

Here is the code snippet which uses setNativeProps and Refs.

In above code, render method will not be called when we click on clear button or text is changed!!! So cool, all the component will not be re-rendered.

We can change any props of a component using setNativeProps and Refs without re-render()!!!!!

That's all…..

If this article helps you then please clap….

--

--