What is the best practice to setState() a class object in React? - javascript

So let's assume I have this code
import {useState} from 'react'
class Something{
counter:number
constructor(counter:number){
this.counter = counter
}
}
function functionalComponent(){
const [state, setState] = useState<Something>(new Something(5))
//other codes .....
function changeState(){
//see below
}
return (
<>
<h1>{state.counter}</h1>
<button onClick={changeState}>Increment</button>
</>
)
}
export default functionalComponent
Now at some point, I want to change the state to have counter increment 1, the below code works but...
function changeState(){
state.counter += 1
setState(state)
}
And before you all start shouting in the comments, I know that we shouldn't mutate the state directly and instead create a new state and pass it on to the setState. But the thing is for js objects and arrays we can simply use the spread operators, but I couldn't find anything simpler for class objects.
So my question is "What should be the best approach for situations like this?"
One I could think of and is using
function changeState(){
let newState = new Something(state.counter+1)
setState(newState)
}
But it becomes counter productive if my object contains many fields say 15

You can use your class inside an object and use the spread operator:
const [state, setState] = useState({state:new Something(5)})
state.state.counter = 1
setState({...state})

One Approach that I tried and seems to be close enough is to have a clone function in the class that returns a clone(new Instance). See the below example for a better understanding
class Something{
counter:number
constructor(counter:number){
this.counter = counter
}
clone(){
return new Something(this.counter)
}
}
So this way whenever I'll call clone it will return a new Instance.
Now in the changeState function, we can do
function changeState(){
let newState = state.clone()
newState.counter += 1
setState(newState)
}
These steps ensures that no where the data is mutated as adheres to the principal of React.

While it would be technically possible to create a new Something every time you want to change the state:
const [state, setState] = useState(5)
const something = useMemo(() => new Something(state), [state]);
I'd also first strongly consider whether you need a class inside a functional component at all - it's pretty odd. There's probably a more intuitive solution.
Another option which may or may not work depending on what your actual code contains in the class constructor would be to have the state contain an object for all instance properties:
const [state, setState] = useState({ counter: 5 });
const something = useMemo(() => Object.assign(new Something(), state), [state]);

Lets just use useState and functional components it would make your life way easier..

Related

Getting previous State of useState([{}]) (array of objects)

I am struggling to get the real previous state of my inputs.
I think the real issue Which I have figured out while writing this is my use of const inputsCopy = [...inputs] always thinking that this creates a deep copy and i won't mutate the original array.
const [inputs, setInputs] = useState(store.devices)
store.devices looks like this
devices = [{
name: string,
network: string,
checked: boolean,
...etc
}]
I was trying to use a custom hook for getting the previous value after the inputs change.
I am trying to check if the checked value has switched from true/false so i can not run my autosave feature in a useEffect hook.
function usePrevious<T>(value: T): T | undefined {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance property on a class
const ref = useRef<T>();
// Store current value in ref
useEffect(() => {
ref.current = value;
}); // Only re-run if value changes
// Return previous value (happens before update in useEffect above)
return ref.current;
}
I have also tried another custom hook that works like useState but has a third return value for prev state. looked something like this.
const usePrevStateHook = (initial) => {
const [target, setTarget] = useState(initial)
const [prev, setPrev] = useState(initial)
const setPrevValue = (value) => {
if (target !== value){ // I converted them to JSON.stringify() for comparison
setPrev(target)
setTarget(value)
}
}
return [prev, target, setPrevValue]
}
These hooks show the correct prevState after I grab data from the api but any input changes set prev state to the same prop values.
I think my issue lies somewhere with mobx store.devices which i am setting the initial state to or I am having problems not copying/mutating the state somehow.
I have also tried checking what the prevState is in the setState
setInputs(prev => {
console.log(prev)
return inputsCopy
})
After Writing this out I think my issue could be when a value changes on an input and onChange goes to my handleInputChange function I create a copy of the state inputs like
const inputsCopy = [...inputs]
inputsCopy[i][prop] = value
setInputs(inputsCopy)
For some reason I think this creates a deep copy all the time.
I have had hella issues in the past doing this with redux and some other things thinking I am not mutating the original variable.
Cheers to all that reply!
EDIT: Clarification on why I am mutating (not what I intended)
I have a lot of inputs in multiple components for configuring a device settings. The problem is how I setup my onChange functions
<input type="text" value={input.propName} name="propName" onChange={(e) => onInputChange(e, index)} />
const onInputChange = (e, index) => {
const value = e.target.value;
const name = e.target.name;
const inputsCopy = [...inputs]; // problem starts here
inputsCopy[index][name] = value; // Mutated obj!?
setInputs(inputsCopy);
}
that is What I think the source of why my custom prevState hooks are not working. Because I am mutating it.
my AUTOSAVE feature that I want to have the DIFF for to compare prevState with current
const renderCount = useRef(0)
useEffect(() => {
renderCount.current += 1
if (renderCount.current > 1) {
let checked = false
// loop through prevState and currentState for checked value
// if prevState[i].checked !== currentState[i].checked checked = true
if (!checked) {
const autoSave = setTimeout(() => {
// SAVE INPUT DATA TO API
}, 3000)
return () => {
clearTimeout(autoSave)
}
}
}
}, [inputs])
Sorry I had to type this all out from memory. Not at the office.
If I understand your question, you are trying to update state from the previous state value and avoid mutations. const inputsCopy = [...inputs] is only a shallow copy of the array, so the elements still refer back to the previous array.
const inputsCopy = [...inputs] // <-- shallow copy
inputsCopy[i][prop] = value // <-- this is a mutation of the current state!!
setInputs(inputsCopy)
Use a functional state update to access the previous state, and ensure all state, and nested state, is shallow copied in order to avoid the mutations. Use Array.prototype.map to make a shallow copy of the inputs array, using the iterated index to match the specific element you want to update, and then also use the Spread Syntax to make a shallow copy of that element object, then overwrite the [prop] property value.
setInputs(inputs => inputs.map(
(el, index) => index === i
? {
...el,
[prop] = value,
}
: el
);
Though this is a Redux doc, the Immutable Update Patterns documentation is a fantastic explanation and example.
Excerpt:
Updating Nested Objects
The key to updating nested data is that every level of nesting must be
copied and updated appropriately. This is often a difficult concept
for those learning Redux, and there are some specific problems that
frequently occur when trying to update nested objects. These lead to
accidental direct mutation, and should be avoided.

React.js State updating correctly only once, then failing [duplicate]

This question already has answers here:
Using a Set data structure in React's state
(2 answers)
Closed 1 year ago.
I have a parent and a child component. There are 3 props the parent provides out of which 1 is not updating correctly.
Following is the parent component. The prop in question is selectedFilters (which is an object where keys are mapped to sets) and the relevant update function is filterChanged (this is passed to the child)
import filters from "../../data/filters"; //JSON data
const Block = (props) => {
const [selectedFilters, setSelectedFilters] = useState({versions: new Set(), languages: new Set()});
console.log(selectedFilters);
const filterChanged = useCallback((filter_key, filter_id) => {
setSelectedFilters((sf) => {
const newSFSet = sf[filter_key]; //new Set(sf[filter_key]);
if (newSFSet.has(filter_id)) {
newSFSet.delete(filter_id);
} else {
newSFSet.add(filter_id);
}
const newSF = { ...sf, [filter_key]: new Set(newSFSet) };
return newSF;
});
}, []);
return (
<FilterGroup
filters={filters}
selectedFilters={selectedFilters}
onFilterClick={filterChanged}
></FilterGroup>
);
};
export default Block;
The following is the child component: (Please note that while the Filter component runs the filterChanged function, I think it is irrelevant to the error)
import Filter from "./Filter/Filter";
const FilterGroup = (props) => {
const { filters, selectedFilters, onFilterClick } = props;
console.log(selectedFilters);
const filter_view = (
<Container className={styles.container}>
{Object.keys(filters).map((filter_key) => {
const filter_obj = filters[filter_key];
return (
<Filter
key={filter_obj.id}
filter_key={filter_key}
filter_obj={filter_obj}
selectedFilterSet={selectedFilters[filter_key]}
onFilterClick={onFilterClick}
/>
);
})}
</Container>
);
return filter_view;
};
export default FilterGroup;
When running the application, I find that the selectedFilters updates correctly only once. After that, it only changes temporarily in the main Block.tsx, but eventually goes back to the first updated value. Also, FilterGroup.tsx only receives the first update. After that, it never receives any further updated values.
Here are the logs:
After some experimentation, it is clear that the problem originates from the filterChanged function. But I cannot seem to figure out why the second update is temporary AND does not get passed on to the child.
Any ideas? Thanks in advance.
(If any other info is required, pls do mention it)
I don't think you actually want your filterChanged function to be wrapped with useCallback, especially with an empty deps array. with the empty deps array, I believe useCallback will fire once on initial render, and memoize the result. You may be able to add filter_key and filter_id to the dependency array, but useCallback tends to actually slow simple functions down, instead of adding any real performance benefit, so you may just want to get rid of the useCallback completely and switch filterChanged to a regular arrow function.

What is the scoping logic behind React states being used inside functions in custom hooks?

So say you have a custom hook:
useCustomHook()=>{
const [state, setState] = React.useState(0);
const modifyState = ({state, n}) => {setState(state + n);}
/*Does state need to be included as an argument/parameter here in modifyState? If, alternatively,
const modifyState = ({n}) => {setState(state + n)};
Will state always be 0 in the scope of modifyState, since that was its value when the function was
created originally. So everytime modifyState is called, it is equivalent to (n)=>setState(0+n) ?
*/
return [state, modifyState];
}
const FunctionalComponent = () => {
const [state, modifyState] = useCustomHook();
const n = 5;
modifyState({state,n}) /* Does state need to be passed here? (since useCustomHook already has its own
copy of state) */
//... logic ....
return <div></div>
}
From doing some testing in the console, it appears that state doesn't need to be passed as an argument to modifyState. But, I'm confused as to the scoping logic behind this, and am unsure if the behavior hooks would change it. Could someone explain the logic behind this?
Instead of passing the state you can make use of function implementation of setState. Something like this:
const modifyState = (n) => {
setState(state => state + n);
}
Ref: https://reactjs.org/docs/hooks-reference.html#functional-updates

How to Pass React form state from app to multiple components (functional)

I'm still fairly new to React, so I'm sorry if this is a repetitive post. I'm working with React to create a form that spreads across different pages. The idea is to have the type of form you'd receive from a job application. One that has multiple steps.
I have different components made for each step of the form. The first page is a home page. Imagine a button to take you to the create page. Then you see the Create page. There is a small form with an amount and name. When you click the next page, you'll see the Customize page. There you can edit your budget by priority.
Here in my poorly drawn picture, I have the app obviously, and a budget homepage to manage state across it's children. I figured I should do it this way because, well it's the only way I know how. The problems I have, are one: I don't know how to properly pass state throughout the components. Two: I don't even know if what I'm doing is correct. The React docs use forms in Class based components, which sort of helps, but I can't configure it to my problem.
Any help or suggestions are greatly appreciated. Also I want to show code from the Budget Page.
import React, { useState, useEffect, useRef } from "react";
import BudgetResultsPage from './BudgetResultsPage';
const [count, setState] = useState(0);
const handleStateCount = () => {
if(count>3) {count = 0;}
return setState(count + 1);
}
if(count === 0) {
console.log(`homepage state ${count}`)
return (
<div className={Styles.Calculator}>
<BudgetHomePage setState={count} handleStateCount={handleStateCount}/>
</div>
)
} else if(count===1) {
console.log(`budget create state ${count}`)
return (
<div className={Styles.Calculator}>
<CalculatorHeader />
<CreateBudget setState={count} handleStateCount={handleStateCount} setAmount={amount} handleAmount={handleAmount}/>
</div>
)}
There are obviously more imports for the other pages and more code passed in the component. This is just a snippet of the way I'm handling the components.
It's probably silly, but I'm creating a count in state, then when part of the form is submitted, the count goes up and it changes the page based on what the count is at. Works great for just one state, but I'm having problems with adding more state to it.
Thanks again!
I have written an example functional components illustrating some of your questions. I wrote this at home and only had notepad++ so might not compile if you copy paste. The comments will explain your questions
import React from 'react';
import Create_budget_page from './Create_budget_page.js';
const BudgetPage = props => {
// State 1: assigning one value to the state.
// State 2: assinging a list to the state.
// State 3: assinging a object to the state.
const [simple_state, set_simple_state] = useState(false);
const [list_state, set_list_state] = useState(["Hello","World","!"]);
const [object_state, set_object_state] = useState(
{
curmenu: "human_bios",
height: "196cm",
weight: "174lbs",
eye_colour: "blue",
hair_colour: "dirty_blonde"
}
);
// there are several possiblities, here's one with a list of objects
const [list_objects, set_list_objects] = useState(
[
{count: 69, wasClicked: false},
{count: 420, wasClicked: true},
// endless possibilities, the tricky part is properly correctly updating your states deep in the list
{integers: [1,5,2,3], keys: {isAlive: false, cur_menu: "config_menu"}}
]
);
// this function updates the state that stores an object
// arguments:
// new_values_object: the programmer passes in a object to the function with the values they want to update
// an example of calling this function in a child functional component:
// props.update_object_state({height: "165cm", weight: "143lbs", hair_colour: "black"});
function update_object_state(new_values_object){
set_object_state(prevState => {
const new_obj = prevState;
// loop through object keys and update the new_obj with the object passed in as a argument
for (var key in new_values_object){
new_obj[key] = new_values_object[key];
}
// returning the new_object will update the object_state
return new_obj;
})
}
// conditionally render based on state
switch(object_state["curmenu"]){
case "home_page":
return (
// pass in
// all props, 1 prop, state
<Create_budget_page {...props} parent_id={prop.parent_id} simple_state={simple_state} list_objects={list_objects}/>
) ;
break;
// pass in function
case "human_bios":
return (
<div className="error_page" onClick={() => {props.update_parent_state({error_occured: true})}}>This is an Error Page, click me to report diagnostics</div>
);
break;
// if none of cases are met default code executes
default:
// renders nothing
return null;
}
}
Which kind of problems are you experiencing? I assume that the part of code you left there is inside a component body (a function, as you are using functional way).
You should have no problems passing multiple props to child components even though you have to keep in mind other approaches (excesive number of props means something is wrong in general...)
Let me know if you have more questions.
EDIT:
Suppose you have that ResultsPage child component and in your parent component you do something like:
<ResultsPage someProp={someValue} someOtherProp={someOtherValue} />
Then in your child component you can manage those props like this:
const ResultsPage = (props) => {
// props is an object like this: { someProp: someValue, someOtherProp: someOtherValue}
... // and in the body of the function you can manipulate it however you want
}
Generally it is better to destructure your props variable in the param directly instead of always do props.someProp, etc. like this:
const ResultsPage = ({someProp, someOtherProp}) => { ... }
More info about destructure here

How does React.useState triggers re-render?

import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In the above example whenever setCount(count + 1) is invoked a re-render happens. I am curious to learn the flow.
I tried looking into the source code. I could not find any reference of useState or other hooks at github.com/facebook/react.
I installed react#next via npm i react#next and found the following at node_modules/react/cjs/react.development.js
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
On tracing back for dispatcher.useState(), I could only find the following ...
function resolveDispatcher() {
var dispatcher = ReactCurrentOwner.currentDispatcher;
!(dispatcher !== null) ? invariant(false, 'Hooks can only be called inside the body of a function component.') : void 0;
return dispatcher;
}
var ReactCurrentOwner = {
/**
* #internal
* #type {ReactComponent}
*/
current: null,
currentDispatcher: null
};
I wonder where can I find dispatcher.useState() implementation and learn how it triggers re-render when setState setCount is invoked.
Any pointer would be helpful.
Thanks!
The key in understanding this is the following paragraph from the Hooks FAQ
How does React associate Hook calls with components?
React keeps track of the currently rendering component. Thanks to the Rules of Hooks, we know that Hooks are only called from React components (or custom Hooks — which are also only called from React components).
There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.
(This also explains the Rules of Hooks. Hooks need to be called unconditionally in the same order, otherwise the association of memory cell and hook is messed up.)
Let's walk through your counter example, and see what happens. For simplicity I will refer to the compiled development React source code and React DOM source code, both version 16.13.1.
The example starts when the component mounts and useState() (defined on line 1581) is called for the first time.
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
As you have noticed, this calls resolveDispatcher() (defined on line 1546). The dispatcher refers internally to the component that's currently being rendered. Within a component you can (if you dare to get fired), have a look at the dispatcher, e.g. via
console.log(React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current)
If you apply this in case of the counter example, you will notice that the dispatcher.useState() refers to the react-dom code. When the component is first mounted, useState refers to the one defined on line 15986 which calls mountState(). Upon re-rendering, the dispatcher has changed and the function useState() on line 16077 is triggered, which calls updateState(). Both methods, mountState() on line 15352 and updateState() on line 15371, return the count, setCount pair.
Tracing ReactCurrentDispatcher gets quite messy. However, the fact of its existence is already enough to understand how the re-rendering happens. The magic happens behind the scene. As the FAQ states, React keeps track of the currently rendered component. This means, useState() knows which component it is attached to, how to find the state information and how to trigger the re-rendering.
setState is a method on the Component/PureComponent class, so it will do whatever is implemented in the Component class (including calling the render method).
setState offloads the state update to enqueueSetState so the fact that it's bound to this is really only a consequence of using classes and extending from Component. Once, you realize that the state update isn't actually being handled by the component itself and the this is just a convenient way to access the state update functionality, then useState not being explicitly bound to your component makes much more sense.
I also tried to understand the logic behind useState in a very simplified and basic manner, if we just look into its basic functionalities, excluding optimizations and async behavior, then we found that it is basically doing 4 things in common,
maintaining of State, primary work to do
re-rendering of the component through which it get called so that caller component can get the latest value for state
as it caused the re-rendering of the caller component it means it must maintain the instance or context of that component too, which also allows us to use useState for multiple component at once.
as we are free to use as many useState as we want inside our component that means it must maintain some identity for each useState inside the same component.
keeping these things in mind I come up with the below snippet
const Demo = (function React() {
let workInProgress = false;
let context = null;
const internalRendering = (callingContext) => {
context = callingContext;
context();
};
const intialRender = (component) => {
context = component;
workInProgress = true;
context.state = [];
context.TotalcallerId = -1; // to store the count of total number of useState within a component
context.count = -1; // counter to keep track of useStates within component
internalRendering(context);
workInProgress = false;
context.TotalcallerId = context.count;
context = null;
};
const useState = (initState) => {
if (!context) throw new Error("Can only be called inside function");
// resetting the count so that it can maintain the order of useState being called
context.count =
context.count === context.TotalcallerId ? -1 : context.count;
let callId = ++context.count;
// will only initialize the value of setState on initial render
const setState =
!workInProgress ||
(() => {
const instanceCallerId = callId;
const memoizedContext = context;
return (updatedState) => {
memoizedContext.state[instanceCallerId].value = updatedState;
internalRendering(memoizedContext);
};
})();
context.state[callId] = context.state[callId] || {
value: initState,
setValue: setState,
};
return [context.state[callId].value, context.state[callId].setValue];
};
return { useState, intialRender };
})();
const { useState, intialRender } = Demo;
const Component = () => {
const [count, setCount] = useState(1);
const [greeting, setGreeting] = useState("hello");
const changeCount = () => setCount(100);
const changeGreeting = () => setGreeting("hi");
setTimeout(() => {
changeCount();
changeGreeting();
}, 5000);
return console.log(`count ${count} name ${greeting}`);
};
const anotherComponent = () => {
const [count, setCount] = useState(50);
const [value, setValue] = useState("World");
const changeCount = () => setCount(500);
const changeValue = () => setValue("React");
setTimeout(() => {
changeCount();
changeValue();
}, 10000);
return console.log(`count ${count} name ${value}`);
};
intialRender(Component);
intialRender(anotherComponent);
here useState and initialRender are taken from Demo. intialRender is use to call the components initially, it will initialize the context first and then on that context set the state as an empty array (there are multiple useState on each component so we need array to maintain it) and also we need counter to make count for each useState, and TotalCounter to store total number of useState being called for each component.
FunctionComponent is different. In the past, they are pure, simple. But now they have their own state.
It's easy to forget that react use createElement wrap all the JSX node, also includes FunctionComponent.
function FunctionComponent(){
return <div>123</div>;
}
const a=<FunctionComponent/>
//after babel transform
function FunctionComponent() {
return React.createElement("div", null, "123");
}
var a = React.createElement(FunctionComponent, null);
The FunctionComponent was passed to react. When setState is called, it's easy to re-render;

Categories

Resources