[WP] 10.02.2023 | react-state

fig 1.1 react state lifecycle


 --------------------------------------------------------------------

Hello and welcome back in another blog post about my front-end/UI programming journey. Recently I started to process second module of The Joy of React course. It describes use of basic react state control method – useState. State variables and state setters are declared within component function before it returns. useState allows to define default value for state variable – it will be assigned during first renderof the component (ComponentDidMount). After that each call to setState method will trigger react re render of the component.

Module 2 also explains how to pass functions together with arguments usings JSX markup. It is possible to achieve by wrapping handler in arrow function eg. onClick = ()=>{handler(arg1, arg2)}

Updating state is asynchronous / state arrays and objects shouldnt be mutated. The solution for this problem is declaring new variable/copying an array or object. Applying changes required and finally call to the state setter passing created and altered variable as an argument. calling setter trigers react to re-render the element.


Edit:


immer js library(standalone or used within redux-toolkit) handles creating new object, requested mutations and assignment to state under the hood.


Data binding is defined as binding a bit of react state with particular input. Consequently we creating controlled input. It involves binding an input value to react state variable // value={stateVar} and passing appropriate handler to onChange event listener. // onChange={(event)=>setStateVar(event.target.values}. Within controlled input some value need to be passed set as default variable state( undefined cannot be passed ) On the other hand we can set uncontrolled input by omiting passing value to value attribute. React will render the input but will not controll it contents.


React emits syntentic events characteristic for react. Classic DOM events are available as nativ property of react synthetic event. When defining some inputs in react it is advised to use <form> tags and apropriately handled submit event. other keywords for form are <fieldset> < legend> onSubmit <input type=”submit”>. Later sound revision of diferent types of form inputs were revised: text, textarea, checkbox, radio button(name unique within group used to make all choices visible to the user.), Select, Range, Color.


Props vs State. Former is used to pass data from parent element downwards(one-direction). Latter is applied to local state controlled within single component. I have paid particular attention to „Lift it up” react covention. It is about synchronising state of two elements. At first we need to find common parent element(closest common ancestor). Then place required piece of state within parent component and then pass state variable via props and pass specific handler to each child element. This enables each and every change within one of the elements to triger shared state change and affect the behaviour of the latter component bound to this state.


The following terms may interest you my dear reader: lift it up boilerplate code; lift it up vs two-way binding. Each component within an app is to have sigular source of truth – the entity that affects its state.


use state setter as child onChange event handler and wrap it up in arrow function. Before that pass the setter from „lifted up” state to children via props. Last but not least it is crucial to mention dynamic key generation pattern. All items generated by mapping an array of data should hold a key attribute specific for react mechanics. it is unique value that allows react to distinguish rendered items and boost performance in case of any changes in generated UI and necesity to re-render. Array indexes shoudlnt be used as id in cases other than static(no removing elemnts, elements are not changing places). Id prop should be attached to mapped objects. id may be assigned with use of basic Math.random function or more fancy crypto.randomUUID() function.


Reducer is a function with switch or if/else statement specifying instructions for every action dispatched by event handlers on components. Event handlers dispatch actions. Reducer handles actions. reducer may be placed in separate module. Reducer should be pure function(no side effects). Each action describes single user interaction(which can trigger state change in many places). When working with reducers additional libaries may be applied such as immer library(draft object). Reducer requires more code to be written but helps with app debugging and testing.


Sleppy but hardworking

g-marcin

Komentarze

Popularne posty z tego bloga

[WP] 23.06.2023 | subjects

15.07.2024 | simplicity

[WP] 05.06.2023 | angular-intro