react-intricacies
This post is about the problems that developers that are new to React might face.
The first thing is understanding that although most of the designing of a React component is done inside render() function (and its helper functions), some behavior of the comoponent can be defined only after it is mounted.
For example, I have a change in Open Source software called Recharts where I have added the ability to move inside a pie chart using arrow keys. There was some behavior that I had to define in componentDidMount(). This is the function which is executed after React components are mounted in the DOM of the browser.
Why did I need to put the behavior in componentDidMount()?
The focus has to move to different sectors based on the arrow keys. You can’t focus on React component. You can only focus on the actual HTML Element that is rendered from the React component. So After the sectors in pie chart are mounted in the browser DOM, we can tell the browser to move the focus according to the arrow keys.
Another weirdness in React is that the reference that points to a mounted React component can be null when we expect otherwise. React docs say this about the weirdness:
“If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element.”
For example if the component returned by your render function contains a div like below:
<div ref={ref => { this.inputRef = ref; }} />
the inputRef will be set to null and then to the actual HTML Element each time there is an update that causes render() to be called.