Thinking in React.

Thinking in React.

One of the key highlights during the process of learning react is the transition from JS to JSX and DOM to VDOM.

The DOM represents the document as nodes and objects, as a result it helps or facilitates the programming languages to interact with the page.

Then how different is the Virtual DOM from DOM? A Virtual DOM is when React creates their own representation of the DOM as a JavaScript object.

What we will try and explore today is the possibility of visualizing the DOM and try and understand the changes in the DOM after an event.

Lets consider an example of a View. A View is a state of function. Change in state changes view. It is important to note that the whole process from ideating, breaking the UI down and coding and then rendering can be broken down into essentially four steps

Initial State ->Initial View ->Event ->New State ->New View

Note: There is only change in state.

Lets consider the example below:

  • Initial state: initialCount: 0

  • initial View: view: display the count

  • Event: check to see which event is clicked (increment or decrement)

  • New state: update the initialCount (increase or decrease)

  • New view: view: display the count

As mentioned earlier State stands as the only difference. Event acts as the initiator and View renders the final state


const counter =() =>{
  const [count, setCount] = useState(0);

  const decrementCountHandler=()=> {
    setCount((prevCount) => prevCount - 1);
  }

  const incrementCountHandler=()=> {
    setCount((prevCount) => prevCount + 1);
  }

  return (
    <div>
      <button onClick={decrementCountHandler}>-</button>
      <div>{count}</div>
      <button onClick={incrementCountHandler}>+</button>
    </div>
  );
}

Depending on the change in state variable the view here updates itself as well.

Note: State updates needs to be in pure.