React useState(0) vs useState( () => 0 ) - reactjs

I saw React codes generally use arrow function for setState(). However, for useState(), I see that they just put a number, eg useState(0) instead of arrow function, ie useState( () => 0 )
Are there any reasons why I would want to use an arrow function in useState ? Is it alright to use only arrow functions for ALL React hook regardless, including initialising the hook. Any gotcha ? Thanks very much.

For your simple case it does not matter. You are just making an extra function call which returns a value without any computation.
But in case your initial state is a result of an expensive computation you can use a function.
Using the below
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});
instead of
const [state, setState] = useState(someExpensiveComputation(props));
matters greatly.
The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded.
So even when your value is disregarded you would be making that expensive computation. You can provide a function in your useState which will only run on the very first render, like in the second case above. [Link](The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded.)

As far as I know, the arrow functions in state setter permit use the previous state.
For example:
const [message, setMessage] = useState('hello ')
... # Receive data from a form or API, etc.
let name = 'Richard'
setMessage(old_state => old_state + name) # 'hello Richard'
This way, you can create counter or reuse some data of the previous state.
Use setState(new_vale) is totally correct for reset the value.

Related

Why is there a function call in a useState() hook in React sometimes? And what does it mean? [duplicate]

I am new to react Hooks. Am trying to make use of useState in my code. While I was using it I found a term "Lazy initial state"
https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});
But I am not able to think of any use case where this lazy initialising of state will be useful.
Like say my DOM is rendering and it needs the state value, but my useState has not initialised it yet! And say if you have rendered the DOM and the someExpensiveComputation has finished, the DOM will re-render!
The value passed to the useState hook in the initial render is the initial state value, and gets disregarded in subsequent renders. This initial value can be the result of calling a function as in the following situation:
const Component = () => {
const [state, setState] = useState(getInitialHundredItems())
}
But note that getInitialHundredItems is unconditionally and needlessly called on each render cycle.
For use cases like this instead of just calling a function that returns a value you can pass a function which returns the initial state. This function will only be executed once (initial render) and not on each render like the above code will. See Lazy Initial State for details.
const Component = () =>{
const [state, setState] = useState(getInitialHundredItems)
}

Combining useState and useRef in ReactJS

I have some variables of which I need the reference as well as the state. I found something here, that helped me: https://stackoverflow.com/a/58349377/7977410
Pretty much it just kept two variables synchronized (in pseudo code):
const [track, setTrack] = useState('INIT');
const trackRef = useRef('INIT');
// Whenever changing, just both are updated
setTrack('newValue');
trackRef.current = 'newValue';
I was wondering if it was beneficial to combine those two into a new hook. Something like this:
const useStateRef(initialState: any) {
const [state, setState] = useState<typeof initialState>(initialState);
const ref = useRef<typeof initialState>(initialState);
useEffect(() => {
setState(ref);
}, [ref]);
return [state, ref];
}
What would be the best way to do this? Is it even critical to do something like this?
(The background is, I have some self-repeating functions, that need the reference to change what they are doing. But I also need the state variable to rerender visible changes when the same variables are changing... Maybe there is a completely different way to do this, but I am still curious about this approach.)
It's possible, but to make the typings proper, you should use generics instead of any, and the effect hook needs to be reversed - change the ref.current when the state changes. You'll also want to return the state setter in order to change the value in the consumer of useStateRef.
const useStateRef = <T extends unknown>(initialState: T) => {
const [state, setState] = useState(initialState);
const ref = useRef(initialState);
useEffect(() => {
ref.current = state;
}, [state]);
// Use "as const" below so the returned array is a proper tuple
return [state, setState, ref] as const;
};
Or, to update synchronously, remove the effect hook:
if (ref.current !== state) ref.current = state;
Also note that there should never be any need to have a ref that only ever contains a primitive. const trackRef = useRef('INIT'); can be refactored away entirely and replaced with track. Refs are generally useful when dealing with objects, like HTMLElements.

confused about Lazy Initialization of React useState [duplicate]

I am new to react Hooks. Am trying to make use of useState in my code. While I was using it I found a term "Lazy initial state"
https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});
But I am not able to think of any use case where this lazy initialising of state will be useful.
Like say my DOM is rendering and it needs the state value, but my useState has not initialised it yet! And say if you have rendered the DOM and the someExpensiveComputation has finished, the DOM will re-render!
The value passed to the useState hook in the initial render is the initial state value, and gets disregarded in subsequent renders. This initial value can be the result of calling a function as in the following situation:
const Component = () => {
const [state, setState] = useState(getInitialHundredItems())
}
But note that getInitialHundredItems is unconditionally and needlessly called on each render cycle.
For use cases like this instead of just calling a function that returns a value you can pass a function which returns the initial state. This function will only be executed once (initial render) and not on each render like the above code will. See Lazy Initial State for details.
const Component = () =>{
const [state, setState] = useState(getInitialHundredItems)
}

Avoid function to run again and again in ReactJs

I created component which take props and this component filter the props but whenever state is changed it re-assign the variable.
Example:
const Foo = (props) => {
const [state, setState] = useState();
const schema = array_filter(props.data, "schema");
// other Code
}
Everytime when state is changed array_filter method is called. array_filter function is custom function which filter the array. I want to avoid extra running of array_filter function. How can I do that can you please let me know.
I try useRef but not working.
Just cache your result and it only re-calculates as your input is changed which is best in your case:
const schema = React.useMemo(() => array_filter(props.data, "schema"), [props.data]);

When to use useState initial value as function?

What is the case where you use useState's initial value as a function?
Is there any difference from just passing a value?
e.g.
const [state, setState] = useState(() => someValue)
You use it when you want the computation of that initial state to happen only once. Because if you use an expression instead say:
const [state, setState] = useState(compute())
The compute runs on other renders too, just its value is ignored after first* render.
So if you do:
const [state, setState] = useState(() => compute())
Now, compute will run only once.
From the docs:
const [state, setState] = useState(initialState);
The initialState argument is the state used during the initial render.
In subsequent renders, it is disregarded. If the initial state is the
result of an expensive computation, you may provide a function
instead, which will be executed only on the initial render
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});
* Well if it is strict mode then it could be the value of first render gets ignored too due to double invoking the render method. But this is not important for this answer. Because the value would now be ignored after second render.
If you want to use useState's initial value as a function, you need to use currying :
const [state, setState] = useState(() => () => someValue);
This is because in the documentation, useState executes the provided function and considers its result as the initial value.
Using currying, () => someValue is returned and considered to be the intial value.
When we have some heavy computation to initialize the state, we should use the function. And this is lazy initialization of the state. Here is a well-written blog on react state lazy initialization by kentcdodds.
The reason why wrapping in a function is less computationally heavy is because react will rerun the component function when props change. If useState() has a computation inside like useState(heavyComputation()), JavaScript will run heavyComputation(), but in useState(()=>heavyComputation()), JavaScript will not run heavyComputation(), but will pass in the curried function, and useState knows not to rerun this function.
Normal
Render 1: useState(heavyComputation()) //JavaScript calls heavyComputation
Render 2: useState(heavyComputation()) //JavaScript calls heavyComputation
Render 3: useState(heavyComputation()) //JavaScript calls heavyComputation
...
Wrapped in Function (curried)
Render 1: useState(()=>heavyComputation()) //useState() calls heavyComputation
Render 2: useState(()=>heavyComputation()) //useState() uses the value from the previous render so heavyComputation() is not called
Render 3: useState(()=>heavyComputation()) //useState() uses the value from the previous render so heavyComputation() is not called
...

Resources