|The Programmers Guide To React
|Written by Ian Elliot
|Monday, 05 June 2017
Page 3 of 3
React The jQuery Way
This is an object with a constructor that sets props and initial state and a render and an inc method to update state. You would use this by creating and instance and then rendering it:
Of course you can use inc to change state and update
No need for a setState method because the inc function automatically does a render. At this point you could argue that this isn't the same as the React component because it provides no facilities for building up a hierarchy of elements and no intelligent rendering. However even with this simple component you can build up a hierarchy simply using HTML. The rendering issue is slightly more subtle but in a component made of nested HTML elements all you would have to do is make sure the state update methods simply updated the sub-elements that had changed.
The standard example of the problem of bulk re-rendering is to include an input element. Change the render method to:
If you try this out you can enter something into the Input element, but as soon as you click the button to update the count whatever was showing is blanked because the render wipes out the entire section of the DOM including the input.
However, there is nothing to say we have to re-render the complete component. First we change the definition of the component so that the reference to the div is saved as a property:
You can see that now we have a property that lets other methods reference the div and this means we can write the inc function as:
Now only the div is updated and anything entered into the Input element is preserved during a state update. You can also see that this approach would be used to build more complex components.
You can argue that this is messy, but it is also simple, direct and efficient. If you only update the parts of the component that have changed you don't have to implement a virtual DOM and you don't have to have a complex rendering algorithm.
The Rest of React
What exactly then does the raw React give you?
The only other major part of React is JSX.
React - A Verdict?
Having said all of this, it is still possible to see why some programmers like React - it saves them from having to think and all programmers are lazy. The biggest loser in React's success is the W3C standard Web Components, a true open source cross platform solution to creating components that is also powerful enough for most tasks.
or email your comment to: firstname.lastname@example.org
|Last Updated ( Saturday, 30 July 2022 )