How does useState update our state? - javascript

This is a very detailed question but im wondering...
let [state, updateState] = useState()
that piece of code returns an initial state, but when we use updateState, how does react actually go into our code and change that "state" ,which is an already updated value? How do they have access to our code to change it like that?

Initial state is stored in [useState("INITIAL-STATE_VALUE")]. and This statement takes toe parameter's first one is the name of state and the second one is the function which update the state when you call it.
So whenever you called that function that will update your state according to you..

Related

sample state in the next line to setState in reactjs

I have a react js question where I am unsure if I can sample a state right after it has been set. Example code below
const [state, setState] = useState<boolean>(false);
setState(val => !val);
axios.post(val);
I think the setState is a call which schedules the state change and then the react engine will eventually change it. So after executing the setState on the next line if I sample 'val' it will be 'false'.
If the above is true, I have a usecase wherein in a single execution flow i need to process and change a state and send the processed state to the backend.
Now, to bend around the above issue I see 2 paths.
Sample the state in a local var. process the var and setState the var and send the var
var stateL = !state;
setState(stateL);
axios.post(stateL);
I use a new state variable trigger and do the axios call on the useEffect of this new state. (i am not using the original state in the useEffect as there are many other changes possible for this state which doesnt need an axios call)
const [triggerBackend, setTriggerBackend] = useState(false)
setState(val => !val);
setTriggerBackend(val => !val);
useEffect(() => {
axios.post(state)
}, [triggerBackend])
I am not sure if '2' is race free as well, so leaning more on '1'.
So my question is, is the way a problem like this can be solved or are there better solutions.
Thanks in advance.

When does React call a component constructor function and what's like the execution flow?

Say I have a simple component like this one:
export default function Foo({someProp}) {
const a = Math.random();
return <div>{a}{someProp}</div>
}
As far as I know, when someProp updates, React will trigger a re-render. Will it execute the whole Foo function once again and reassign const a a new random value? Will the value be displayed in the <div>?
Thank you.
The answer for every one of your question is yes. A re-render is triggered when there is a props change as you said, and also when there is a state change. When re-rendering and also on the first render, everything behaves like in a normal JavaScript function, as far as assigning variables and everything else, except for some things related to React Hooks, like a state made with useState, a ref made with useRef...

React-Redux Slider undefined value when passing onwards the values

This is my first post so I'm sorry if I'm doing it wrong. So, I've started creating a webpage for my portfolio with React and Redux but I hit a point where I can't find the solution or the flaw in my logic. The page is that the user can select a skill and then the pointer to the value he knows. I can save the skills to localStorage but I can't manage to pass the skill value from the slider to save it. If anyone can help with any tip or info of where I m doing wrong please help.
This are some of the components:
slider component
skillsComp whee the slider is passed
listSkills Comp where skillsComp and Slider is passed
redux actions
redux reducer
and this is the console output: console
Problem: Not Dispatching Action
The problems that I'm seeing are in image #1 of the SkillSliderBar component. There might be other issue too, I haven't looked further then this.
First of all, your destructured props are missing the addSkillValue function from mapDispatchToProps.
You defined a function handleChange to call the addSkillValue function, but you never call handleChange. Instead you are calling changeValue which updates the local component state.
You probably don't need a local state at all. You can use the skillValue from mapStateToProps as the value for your inputs. To set the value, call addSkillValue from mapDispatchToProps.
Make sure that the onChange function for your inputs is being called with the value first and not the event. If it is being called with the event then your handleChange would look like:
const handleChange = e => {
addSkillValue(e.target.value);
}
Suggestions: State Shape
It looks like you only have a skill value in your state for the current skill. Probably what you want is to store an array of skill objects with properties name and value. Or possibly a key-value object where the keys are the skill names and the values are the skill values. I'm not sure if you need the currentSkillName. You can update the value for any skill by dispatching an action that contains both the new value and the name of the skill that you are updating.

UseState shows previous value always [duplicate]

This question already has answers here:
The useState set method is not reflecting a change immediately
(15 answers)
Closed 2 years ago.
This is a popular question among all the new react developers but somehow I'm not able to understand the logic behind available solutions. I'm trying to update the state variable using hooks and trying it read the updated value but always it returns a previous value instead of new value. Below is the sequence of my code execution.
onClick={setTransactionAccountId}
on button click, it executes the below code and updates the state but the console.log shows the old value.
const [accountId, setAccountId] = useState(0);
const setTransactionAccountId = e => {
console.log("Clicked ID:", e.currentTarget.value);
setAccountId(e.currentTarget.value);
console.log("accountId:", accountId);
};
console log:
first button click:
Clicked ID: 0
accountId: 0
second button click:
Clicked ID: 1
accountId: 0
could anyone please tell me the reason behind this behaviour and how to tackle it.
accountId won't have been updated this render. You have to wait for the next render for it to be updated. accountId only gets populated at the top of the function component when useState is called. You're in the middle of the render. If you need the actual value, keep pulling it out of e.currentTarget.value.
From react docs
React may batch multiple setState() calls into a single update for
performance.
Because this.props and this.state may be updated asynchronously, you
should not rely on their values for calculating the next state.
State updates may be batched and updated asynchronously, therefore the state may have not updated when console.log() is called. You will get the guaranteed updated result in your next call to useEffect hook.
This is because setState is asynchronous. Executing console.log('accountId:', accountId) before the state has updated will still give you the previous state value. If you add an async/await, that should fix the issue.
const setTransactionAccountId = async (e) => {
console.log('Clicked ID:', e.currentTarget.value)
await setAccountId(e.currentTarget.value)
console.log('accountId:', accountId)
}

Is useState synchronous? [duplicate]

This question already has answers here:
The useState set method is not reflecting a change immediately
(15 answers)
Closed 4 years ago.
In the past, we've been explicitly warned that calling setState({myProperty}) is asynchronous, and the value of this.state.myProperty is not valid until the callback, or until the next render() method.
With useState, how do I get the value of the state after explicitly updating it?
How does this work with hooks? As far as I can tell, the setter function of useState doesn't take a callback, e.g.
const [value, setValue] = useState(0);
setValue(42, () => console.log('hi callback');
doesn't result in the callback being run.
My other workaround in the old world is to hang an instance variable (e.g. this.otherProperty = 42) on the class, but that doesn't work here, as there is no function instance to reuse (no this in strict mode).
You can use useEffect to access the latest state after updating it. If you have multiple state hooks and would like to track the update on only part of them, you can pass in the state in an array as the second argument of the useEffect function:
useEffect(() => { console.log(state1, state2)}, [state1])
The above useEffect will only be called when state1 is updated and you shouldn't trust the state2 value from inside this function as it may not be the latest.
If you are curious about whether the update function created by useState is synchronous, i.e. if React batches the state update when using hooks, this answer provide some insight into it.
Well, if you refer to the relevant docs you'll find...
const [state, setState] = useState(initialState);
Returns a stateful value, and a function to update it.
During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).
The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.
setState(newState);
During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates.
So your new state, whatever it is, is what you've just set in useState, i.e. the value of initialState. It goes directly to state, which updates reactively thereafter. Quoting further from the relevant docs:
What does calling useState do? It declares a “state variable”. Our variable is called count but we could call it anything else, like banana. This is a way to “preserve” some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.
If you'd like to do something whenever your state updates, then just use componentDidUpdate.(docs)

Categories

Resources