Skip to main content

Posts

Showing posts with the label state

Context API in React

The Need  In case of using props in a hierarchy of components, we need to move the data throughout the hierarchy from the leaf node to the root node in order to communicate the data / handlers to the siblings This leaves us with the following 1. The parent components, does not need to know the child component's data but it still gets them inorder to uplift the state 2. Components gets polluted with the props of unused data / handlers 3. Chances are high that after development, in the maintenance phase, these methods might be overwritten or consumed in the wrong component if the maintainer does not have a good understanding and is on a hurry to resolve an issue 4. Data communication is highly linked between unrelated components Illustration The below diagram will illustrate the problem where each components uplifts the state in order to the siblings to get the update or data from their siblings. This causes the root component (<App />) to be fully aware of what is going on in

useState VS useReducer in React

useState vs useReducer Introduction This post does not deal with what a state and a reducer means as it is expected that the user has a little background on what they are and how they work. This post mainly focusses on the doubts that a developer might encounter when they have to choose between a state and a reducer and not clear on when to use which feature. useState =>  This is a good state management tool (mainly used for component state) Suitable to manage individual states where the properties or data are simple like primitive values This is a good option for simple and less dependent data Example:   When we have a input change like radio button that turns on / off the visibility of sections of the DOM, a state is a good fit useReducer =>  This is a good option when objects are used as a state This is a good option to use when there is a complex state update logic to be executed since there is dependency between the individual states This feature helps in moving out the stat