Should I Learn React Java Developer
Thinking in Java: Acquire React and React Hooks with Java Code ☕
As a long-time Java developer, information technology took me a while to understand some of the magics behind React. This postal service is my effort to explicate some of them in Java concepts. It's not meant to provide a strict mapping from Coffee to React.
Below is a React Counter
component. It renders a count number, with a push to increment it. Every time the push button is clicked, the count is added by one and the value is updated on the screen.
blazon Props = { initialCount : number }; type State = { currentCount : number }; class Counter extends React . Component < Props , Land > { // Sets currentCount to initialCount when component is created state : State = { currentCount : this . props . initialCount }; // Renders a text and a button, which increments count by ane when clicked. render () { return ( < div > { this . country . currentCount } < button onClick = { () => this . setState ({ currentCount : this . land . currentCount + ane }) } > Increase </ push button > </ div > ); } } // Renders Counter at root const rootElement = document . getElementById ( " root " ); render (< Counter initialCount = { 0 } />, rootElement );
The same React component can be (sort-of) written in Java:
// The Props course to pass data into Counter, publicly construct-able. public form Props { public final int initialCount ; public Props ( int initialCount ) { this . initialCount = initialCount ; } } public course Counter { // The Land course to hold internal data of Counter, individual simply. private static course State { concluding int currentCount ; Country ( int count ) { this . currentCount = count ; } } private Land country ; private Props props ; individual boolean shouldRender ; // Constructor. Chosen once per component lifecycle. public Counter ( final Props props ) { this . updateProps ( props ); this . setState ( new State ( props . initialCount )); } // Called past external whenever props have changed. public void updateProps ( final Props props ) { this . props = new Props ( props . initialCount ); this . shouldRender = true ; } // Internal state update method for current count. private void setState ( terminal Land newState ) { this . state = newState ; this . shouldRender = truthful ; } // Only allows render when shouldRender is true, i.eastward., props or state changed. public boolean shouldRender () { return this . shouldRender ; } // Returns a 'virtal DOM' node 'Div' that contains a 'Text' node and a 'Push', // which increments count by i when clicked. public ReactNode render () { this . shouldRender = false ; return new Div ( new Text ( this . land . currentCount ), new Button ( "Increment" , new OnClickHandler () { @Override public void onClick () { setState ( new Country ( land . currentCount + i )); } }); ); } } // Renders Counter at root public static void renderAt ( HTMLElement root ) { Counter counter = new Counter ( new Props ( 0 )); root . addChild ( counter ); if ( counter . shouldRender ()) { counter . render (); } ... }
To readers who have a Coffee background, table beneath maps some core React concepts into Java ones.
React Concept | Java Concept |
---|---|
component | grade |
props | Passed-in parameters of constructor or updateProps() method, immutable internally |
state | A set of all individual variables , immutable internally |
setState() | Replaces the previous group of private variables with a new group |
render() | Creates a new view with values practical |
A few interesting things to note here:
props
vs. state
In React, props
are used for external world to communicate with the component, similar to Java constructor and public method parameters. In example above, information technology's used for setting its initial count value.
state
, on the other paw, is used by the component internally, holding data that only matters to the component itself. This is similar to individual variables in Coffee. Nonetheless, a parent component's country
can get a child component's props
. Eastward.g., Counter
's currentCount
is passed into Text
component equally the latter'south props
.
Both props
and country
should exist immutables internally. In React, nosotros never change their internal values directly. Instead, pass in a new props
to the component (example below), and use setState()
for setting a new state
. Note how they are internally final
in Java code above.
No Change, No Render
React only renders the component if either props
or country
has inverse. This allows it to avert unnecessary DOM updates. In above example, the component doesn't re-return until either button is clicked (a country
change) or initialCount
is inverse (a props
change). This is simulated using shouldRender()
method above.
Virtual DOM nodes
render()
returns virtual nodes. They are objects that describes how a certain blazon of UI should be rendered. They are not the finish results. It'due south up to the React engine to decide how UI will be generated and presented on the screen. This allows React to piece of work with different platforms. Due east.g., React.js renders a Html <button>
while React Native renders an Android Button
or iOS UIButton
.
Handle props
Changes
Now, let'due south briefly talk nigh React lifecycles. React provides several lifecycle methods. Today we accept a expect at componentDidUpdate()
.
Let's say we desire the component to reset land.currentCount
if the passed-in props.initialCount
has changed. We tin implement componentDidUpdate()
every bit below:
class Counter extends React . Component < Props , State > { state : State = { currentCount : this . props . initialCount }; // Afterwards props changed, check if initialCount has changed, and then reset currentCount to the new initialCount. componentDidUpdate ( prevProps : Props ) { if ( prevProps . initialCount !== this . props . initialCount ) { this . setState ({ currentCount : this . props . initialCount }); } } return () { ... } }
This may be written in Coffee as:
class Counter { ... // Called past external whenever props have changed. public void updateProps ( final Props props ) { final Props prevProps = this . props ; this . props = new Props ( props . initialCount ); this . shouldRender = true ; this . componentDidUpdate ( prevProps ); } private void componentDidUpdate ( last Props prevProps ) { if ( prevProps . initialCount != this . props . initialCount ) { setState ( new State ( this . props . initialCount )); } } ... } Counter counter = new Counter ( new Props ( 0 )); counter . updateProps ( new Props ( 100 ));
The external world calls updateProps()
to update Counter
'southward props
. Hither, updateProps()
preserves prevProps
, and passes it into componentDidUpdate()
. This allows the component to detect a props
change and make updates accordingly.
Too annotation that setting new props
doesn't require creating a new component instance. In the case above, the same Counter
component is reused with new props
. In fact, React tries to reuse existing components as much as possible using some smart DOM matching and the key
props. Information technology simply creates new components when they cannot be found on the current DOM tree.
React Hooks
If you are learning React, you must larn Hooks every bit it's the new standard (a good affair). Let's quickly look at the equivalent code in React Hooks:
const Counter = ({ initialCount }: Props ) => { const [ currentCount , setCurrentCount ] = React . useState ( initialCount ); React . useEffect (() => { setCurrentCount ( initialCount ); }, [ initialCount ]); return ( < div > { currentCount } < button onClick = { () => setCurrentCount ( currentCount + i ) } > Increment </ button > </ div > ); };
The lawmaking is just much conciser considering many things are subconscious behind each line.
The line below uses React.useState()
. It kills two birds with ane stone (sad, birds 🥺).
const [ currentCount , setCurrentCount ] = React . useState ( initialCount );
- Information technology sets
state.currentCount
asinitialCount
like to the Coffee constructor, and - returns a
setCurrentCount()
part that'south equivalent to thesetState()
method used in Java.
The benefit of using this blueprint is that y'all can break down one single country
object into multiple unproblematic values, each controlled by its own useState()
method.
Side by side, the lines below uses React.useEffect()
to create an effect
, which is run every time the component updates.
React . useEffect (() => { setCurrentCount ( initialCount ); }, [ initialCount ]);
In this case, the effect
is tied to the initialCount
value (note the final parameter of useEffect()
). This tells useEffect
to only run setCurrentCount(initialCount)
when initialCount
changes. This is equivalent to Java code below:
private void componentDidUpdate ( final Props prevProps ) { if ( prevProps . initialCount != this . props . initialCount ) { setState ( new State ( this . props . initialCount )); } }
There are many other magics in React and Hooks that go beyond this post. Leave a comment below if you'd like to larn more than on this topic ❤️❤️❤️
Should I Learn React Java Developer,
Source: https://dev.to/getd/thinking-in-java-learn-react-and-react-hooks-with-java-code-1ohf
Posted by: hesslockonamind.blogspot.com
0 Response to "Should I Learn React Java Developer"
Post a Comment