React Hooks - useState value cannot change - reactjs

Problem
I want to get the value of the updated hooks state whenever I clicked enter.
But I always get the Initial Value, instead of the updated one.
CODE
import React, { useState } from "react";
import ReactDOM from "react-dom";
import ContentEditable from "react-contenteditable";
const ItemCol = props => {
const [value, setValue] = useState("Initial Value");
const onChange = event => {
setValue(event.target.value);
console.log("onChange: " + value);
};
const keyDown = event => {
if (event.keyCode === 13) {
event.preventDefault();
//Value should be changed, but did not change
console.log("Enter Pressed: " + value);
}
};
return (
<ContentEditable
html={value}
onKeyDown={React.useCallback(keyDown)}
onChange={React.useCallback(onChange)}
/>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<ItemCol />, rootElement);
CodeSandBox.io: https://codesandbox.io/embed/pensive-worker-31l3r
Note: keyCode 13 is Enter.
Note 2: I'm using react-contenteditable dependencies. (https://www.npmjs.com/package/react-contenteditable)
Please do help me, as I have this problem for hours. Thanks !

The ContentEditable component seems to memoize the onKeydown method and hence whenever you invoke it, it prints the value from its initial closure which is why you have the initial value always.
To solve this closure issue, you could keep the value in a ref and mutate it
const ItemCol = props => {
const [value, setValue] = useState("Initial Value");
const valRef = useRef(value);
const onChange = event => {
setValue(event.target.value);
valRef.current = event.target.value;
};
const keyDown = event => {
if (event.keyCode === 13) {
event.preventDefault();
//Value should be changed, but did not change
console.log("Enter Pressed: " + valRef.current);
}
};
return (
<ContentEditable
html={value}
onKeyDown={keyDown}
onChange={React.useCallback(onChange)}
/>
);
};
Working demo

#Michael Harley,problem was with closure or with the way react-content-editable onkeydown function setup inside react-content-editable.
Working Demo:- https://codesandbox.io/embed/elated-bohr-jeu4u?fontsize=14
Resource :- https://overreacted.io/a-complete-guide-to-useeffect/

Related

React.Js Input Field looses the focus on every Keystroke

When I press a key for inputting the value, the text field loses the focus and I again need to click on the input field.
import React, { useState } from "react";
import styled from "styled-components";
import Button from "../../UI/Button/Button";
import "./CourseInput.css";
const CourseInput = (props) => {
const [enteredValue, setEnteredValue] = useState("");
const [isValid, setIsValid] = useState(true);
Here is the code to handle input field changes
const goalInputChangeHandler = (event) => {
if (event.target.value.trim().length > 0) {
setIsValid(true);
}
setEnteredValue(event.target.value);
};
Here is the code to handle the form submission.
const formSubmitHandler = (event) => {
event.preventDefault();
if (enteredValue.trim().length === 0) {
setIsValid(false);
return;
}
props.onAddGoal(enteredValue);
setEnteredValue("");
};
const FormControl = styled.form`
// ....some CSS
`;
return (
<form onSubmit={formSubmitHandler}>
<FormControl className={!isValid && " invalid"}>
<label>Course Goal</label>
<input
value={enteredValue}
type="text"
onChange={goalInputChangeHandler}
/>
</FormControl>
<Button type="submit">Add Goal</Button>
</form>
);
};
export default CourseInput;
I've tried to recreate your issue locally and wasn't able to.
However, I believe the input loses focus as you are setting isValid to true, triggering a re-render and therefor input focus gets lost.
Instead of setting isValid in goalInputChangeHandler, leverage useEffect hook, which will allow you to perform side effects (e.g. when changing the value of the input, a side effect is to update the isValid value) like below:
useEffect(() => {
if (enteredValue.length > 0) {
setIsValid(true);
} else {
setIsValid(false);
}
}, [enteredValue]);
const goalInputChangeHandler = (event) => {
setEnteredValue(event.target.value);
};
This also will allow you to update your submit function to be as follows:
const formSubmitHandler = (event) => {
event.preventDefault();
props.onAddGoal(enteredValue);
};
As the useEffect will ensure isValid is correctly updated.

Modifying user input value in React controlled component

I've been stuck on this error for a long time, so I would appreciate some help. Here is a minimally reproducible exmaple:
import "./App.css";
import React, { useState } from "react";
import $ from "jquery";
function App() {
const [value, setValue] = useState("");
const focusHandler = () => {
$("input").on("keypress", (e) => {
let copy = value;
if (e.key === ".") {
e.preventDefault();
copy += " ";
setValue(copy);
}
});
};
const blurHandler = (event) => {
$("input").off("keypress");
setValue(event.target.value);
};
const changeHandler = (event) => {
setValue(event.target.value);
};
return (
<div>
<input
value={value}
onFocus={focusHandler}
onBlur={blurHandler}
onChange={changeHandler}
/>
</div>
);
}
export default App;
On input focus, I'm adding an event listener to look for a . keypress and append a tab (4 spaces) to the input if it is pressed. But when I press . multiple times, the input gets stuck at the first tab, and doesn't move any further (e.g. input permanenetly shows 4 spaces). Using console.log shows me that the value state doesn't seem to be updating in focusHandler and reverts to the original value ("").
An important note is that switching to a class-based component with this.state makes it work. Any insight as to why this is happening?
As mentioned in the comments, jQuery is the wrong tool for the job. Bringing in jQuery is the same as calling DOM methods directly: it's circumventing React and adding additional listeners on top of the ones React already gives you. You can expect misbehavior if you're setting state from multiple handlers unrelated to React. Once you're in React, use the tools it gives you (refs, effects, handlers) to solve the problem.
Worst case scenario is when an approach appears to work, then fails in production, on other people's machines/browsers, when refactoring from classes to hooks or vice-versa, in different versions of React, or for 1 out of 1000 users. Staying well within the API React gives you better guarantees that your app will behave correctly.
Controlled component
For manipulating the input value, you can use both onKeyDown and onChange listeners. onKeyDown fires first. Calling event.preventDefault() inside of onKeyDown will block the change event and ensure only one call to setState for the controlled input value occurs per keystroke.
The problem with this the input cursor moves to the end after the component updates (see relevant GitHub issue). One way to deal with this is to manually adjust the cursor position when you've made an invasive change to the string by adding state to keep track of the cursor and using a ref and useEffect to set selectionStart and selectionEnd properties on the input element.
This causes a brief blinking effect due to asynchrony after the render, so this isn't a great solution. If you're always appending to the end of the value, you assume the user won't move the cursor as other answers do, or you want the cursor to finish at the end, then this is a non-issue, but this assumption doesn't hold in the general case.
One solution is to use useLayoutEffect which runs synchronously before the repaint, eliminating the blink.
With useEffect:
const {useEffect, useRef, useState} = React;
const App = () => {
const [value, setValue] = useState("");
const [cursor, setCursor] = useState(-1);
const inputRef = useRef();
const pad = ". ";
const onKeyDown = event => {
if (event.code === "Period") {
event.preventDefault();
const {selectionStart: start} = event.target;
const {selectionEnd: end} = event.target;
const v = value.slice(0, start) + pad + value.slice(end);
setValue(v);
setCursor(start + pad.length);
}
};
const onChange = event => {
setValue(event.target.value);
setCursor(-1);
};
useEffect(() => {
if (cursor >= 0) {
inputRef.current.selectionStart = cursor;
inputRef.current.selectionEnd = cursor;
}
}, [cursor]);
return (
<div>
<p>press `.` to add 4 spaces:</p>
<input
ref={inputRef}
value={value}
onChange={onChange}
onKeyDown={onKeyDown}
/>
</div>
);
};
ReactDOM.createRoot(document.querySelector("#app"))
.render(<App />);
input {
width: 100%;
}
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="app"></div>
With useLayoutEffect:
const {useLayoutEffect, useRef, useState} = React;
const App = () => {
const [value, setValue] = useState("");
const [cursor, setCursor] = useState(-1);
const inputRef = useRef();
const pad = ". ";
const onKeyDown = event => {
if (event.code === "Period") {
event.preventDefault();
const {selectionStart: start} = event.target;
const {selectionEnd: end} = event.target;
const v = value.slice(0, start) + pad + value.slice(end);
setValue(v);
setCursor(start + pad.length);
}
};
const onChange = event => {
setValue(event.target.value);
setCursor(-1);
};
useLayoutEffect(() => {
if (cursor >= 0) {
inputRef.current.selectionStart = cursor;
inputRef.current.selectionEnd = cursor;
}
}, [cursor]);
return (
<div>
<p>press `.` to add 4 spaces:</p>
<input
ref={inputRef}
value={value}
onChange={onChange}
onKeyDown={onKeyDown}
/>
</div>
);
};
ReactDOM.createRoot(document.querySelector("#app"))
.render(<App />);
input {
width: 100%;
}
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="app"></div>
Uncontrolled component
Here's another attempt using an uncontrolled component. This doesn't have the blinking problem because the DOM element's .value property is synchronously set at the same time as the .selectionStart property and is rendered in the same repaint.
const App = () => {
const pad = ". ";
const onKeyDown = event => {
if (event.code === "Period") {
event.preventDefault();
const {target} = event;
const {
value, selectionStart: start, selectionEnd: end,
} = target;
target.value = value.slice(0, start) +
pad + value.slice(end);
target.selectionStart = start + pad.length;
target.selectionEnd = start + pad.length;
}
};
return (
<div>
<p>press `.` to add 4 spaces:</p>
<input
onKeyDown={onKeyDown}
/>
</div>
);
};
ReactDOM.createRoot(document.querySelector("#app"))
.render(<App />);
input {
width: 100%;
}
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="app"></div>
Don't mix direct DOM manipulation, whether that's vanilla JavaScript or jQuery, with React. There is no need to add an event handler with jQuery here, because your methods are already event handlers. Just use them directly:
const focusHandler = (e) => {
// handle the event here!
}
My solution:
const changeHandler = (event) => {
const key = event.nativeEvent.data;
if (key === ".") {
event.preventDefault();
const initialValue = event.target.value.split(".")[0];
console.log(initialValue);
setValue(initialValue + " ");
} else {
setValue(event.target.value);
}
};

react useRef : current value is undefined

I'm following a beginner's tutorial for the useState and useRef hooks, trying to implement a simple timer in react.
I'm using the interval variable to store the value from setInterval()
On click of start button, I am able to console.log the value of the interval correctly.
However on click of stop button, interval.current is console logged as undefined. The stopTimer() hence does not function as expected.
Why does interval.current print undefined when it is clearly set in startTimer (and logged there)? What am I missing here?
import React, { useState, useRef } from 'react';
const pad = (time) => {
return time.toString().padStart(2, "0");
};
function App() {
const [title, setTitle] = useState("Pomodoro!");
const [timeLeft, setTimeLeft] = useState(5);
const interval = useRef(null);
const startTimer = () => {
interval.current = setInterval(() => {
setTimeLeft((timeLeft) => {
if (timeLeft >= 1) {
return timeLeft - 1;
}
return 0;
});
}, 1000);
console.log(interval.current, " :in start");
}
const stopTimer = (interval) => {
console.log("in stop: ", interval.current);
clearInterval(interval.current);
}
const resetTimer = () => { }
const minutes = pad(Math.floor(timeLeft / 60));
const seconds = pad((timeLeft - minutes * 60));
return (
<div>
<div>{title}</div>
<div>
<span>{minutes}</span>
<span>:</span>
<span>{seconds}</span>
</div>
<div>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
<button onClick={resetTimer}>Reset</button>
</div>
</div>
);
}
export default App;
output in console
6 " :in start"
in stop: undefined
Thanks
I believe it is because you pass a lower scope variable called interval to stopTimer, but when you call stopTimer you do not pass the argument, so it is undefined when you're accessing it.
You probably referring to interval you've defined as ref so you need to just access it without passing interval to stopTimer, try this:
const stopTimer = () => {
console.log("in stop: ", interval.current);
clearInterval(interval.current);
}
Considering what your code is doing, I believe interval should be a state variable and not a ref. That is to say, you should use
const [interval, setInterval] = useState(null);
instead of const interval = useRef(null);
Refs are used to be linked to DOM elements (for instance a form element you wish to refer to when a button is clicked). It's only when a ref variable is correctly referencing a DOM element that their current attribute is defined.

React hook api state is sometimes empty

I am using hook api for managing state, the problem is that state is sometimes empty in handler fucntion.
I am using component for manage contenteditable (using from npm) lib. You can write to component and on enter you can send event to parent.
See my example:
import React, { useState } from "react"
import css from './text-area.scss'
import ContentEditable from 'react-contenteditable'
import { safeSanitaze } from './text-area-utils'
type Props = {
onSubmit: (value: string) => void,
}
const TextArea = ({ onSubmit }: Props) => {
const [isFocused, setFocused] = useState(false);
const [value, setValue] = useState('')
const handleChange = (event: React.FormEvent<HTMLDivElement>) => {
const newValue = event?.currentTarget?.textContent || '';
setValue(safeSanitaze(newValue))
}
const handleKeyPress = (event: React.KeyboardEvent<HTMLDivElement>) => {
// enter
const code = event.which || event.keyCode
if (code === 13) {
console.log(value) // THERE IS A PROBLEM, VALUE IS SOMETIMES EMPTY, BUT I AM SURE THAT TEXT IS THERE!!!
onSubmit(safeSanitaze(event.currentTarget.innerHTML))
setValue('')
}
}
const showPlaceHolder = !isFocused && value.length === 0
const cls = [css.textArea]
if (!isFocused) cls.push(css.notFocused)
console.log(value) // value is not empty
return (
<ContentEditable
html={showPlaceHolder ? 'Join the discussion…' : value}
onChange={handleChange}
className={cls.join(' ')}
onClick={() => setFocused(true)}
onBlur={() => setFocused(false)}
onKeyPress={handleKeyPress}
/>
)
}
export default React.memo(TextArea)
Main problem is that inside handleKeyPress (after enter keypress) is value (from state) empty string, why? - in block console.log(value) // THERE IS A PROBLEM, VALUE IS SOMETIMES EMPTY, BUT I AM SURE THAT TEXT IS THERE!!! I don't understand what is wrong??
The value is empty, because onChange doesn't actually change it, which means
const newValue = event?.currentTarget?.textContent || '';
this line doesn't do what it's supposed to. I think you should read the target prop in react's synthetic events instead of currentTarget. So, try this instead
const newValue = event.target?.value || '';
Hope this helps.

Is it safe to use ref.current as useEffect's dependency when ref points to a DOM element?

I'm aware that ref is a mutable container so it should not be listed in useEffect's dependencies, however ref.current could be a changing value.
When a ref is used to store a DOM element like <div ref={ref}>, and when I develop a custom hook that relies on that element, to suppose ref.current can change over time if a component returns conditionally like:
const Foo = ({inline}) => {
const ref = useRef(null);
return inline ? <span ref={ref} /> : <div ref={ref} />;
};
Is it safe that my custom effect receiving a ref object and use ref.current as a dependency?
const useFoo = ref => {
useEffect(
() => {
const element = ref.current;
// Maybe observe the resize of element
},
[ref.current]
);
};
I've read this comment saying ref should be used in useEffect, but I can't figure out any case where ref.current is changed but an effect will not trigger.
As that issue suggested, I should use a callback ref, but a ref as argument is very friendly to integrate multiple hooks:
const ref = useRef(null);
useFoo(ref);
useBar(ref);
While callback refs are harder to use since users are enforced to compose them:
const fooRef = useFoo();
const barRef = useBar();
const ref = element => {
fooRef(element);
barRef(element);
};
<div ref={ref} />
This is why I'm asking whether it is safe to use ref.current in useEffect.
It isn't safe because mutating the reference won't trigger a render, therefore, won't trigger the useEffect.
React Hook useEffect has an unnecessary dependency: 'ref.current'.
Either exclude it or remove the dependency array. Mutable values like
'ref.current' aren't valid dependencies because mutating them doesn't
re-render the component. (react-hooks/exhaustive-deps)
An anti-pattern example:
const Foo = () => {
const [, render] = useReducer(p => !p, false);
const ref = useRef(0);
const onClickRender = () => {
ref.current += 1;
render();
};
const onClickNoRender = () => {
ref.current += 1;
};
useEffect(() => {
console.log('ref changed');
}, [ref.current]);
return (
<>
<button onClick={onClickRender}>Render</button>
<button onClick={onClickNoRender}>No Render</button>
</>
);
};
A real life use case related to this pattern is when we want to have a persistent reference, even when the element unmounts.
Check the next example where we can't persist with element sizing when it unmounts. We will try to use useRef with useEffect combo as above, but it won't work.
// BAD EXAMPLE, SEE SOLUTION BELOW
const Component = () => {
const ref = useRef();
const [isMounted, toggle] = useReducer((p) => !p, true);
const [elementRect, setElementRect] = useState();
useEffect(() => {
console.log(ref.current);
setElementRect(ref.current?.getBoundingClientRect());
}, [ref.current]);
return (
<>
{isMounted && <div ref={ref}>Example</div>}
<button onClick={toggle}>Toggle</button>
<pre>{JSON.stringify(elementRect, null, 2)}</pre>
</>
);
};
Surprisingly, to fix it we need to handle the node directly while memoizing the function with useCallback:
// GOOD EXAMPLE
const Component = () => {
const [isMounted, toggle] = useReducer((p) => !p, true);
const [elementRect, setElementRect] = useState();
const handleRect = useCallback((node) => {
setElementRect(node?.getBoundingClientRect());
}, []);
return (
<>
{isMounted && <div ref={handleRect}>Example</div>}
<button onClick={toggle}>Toggle</button>
<pre>{JSON.stringify(elementRect, null, 2)}</pre>
</>
);
};
See another example in React Docs: How can I measure a DOM node?
Further reading and more examples see uses of useEffect
2021 answer:
This article explains the issue with using refs along with useEffect: Ref objects inside useEffect Hooks:
The useRef hook can be a trap for your custom hook, if you combine it with a useEffect that skips rendering. Your first instinct will be to add ref.current to the second argument of useEffect, so it will update once the ref changes.
But the ref isn’t updated till after your component has rendered — meaning, any useEffect that skips rendering, won’t see any changes to the ref before the next render pass.
Also as mentioned in this article, the official react docs have now been updated with the recommended approach (which is to use a callback instead of a ref + effect). See How can I measure a DOM node?:
function MeasureExample() {
const [height, setHeight] = useState(0);
const measuredRef = useCallback(node => {
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
}
}, []);
return (
<>
<h1 ref={measuredRef}>Hello, world</h1>
<h2>The above header is {Math.round(height)}px tall</h2>
</>
);
}
I faced the same problem and I created a custom hook with Typescript and an official approach with ref callback. Hope that it will be helpful.
export const useRefHeightMeasure = <T extends HTMLElement>() => {
const [height, setHeight] = useState(0)
const refCallback = useCallback((node: T) => {
if (node !== null) {
setHeight(node.getBoundingClientRect().height)
}
}, [])
return { height, refCallback }
}
I faced a similar problem wherein my ESLint complained about ref.current usage inside a useCallback. I added a custom hook to my project to circumvent this eslint warning. It toggles a variable to force re-computation of the useCallback whenever ref object changes.
import { RefObject, useCallback, useRef, useState } from "react";
/**
* This hook can be used when using ref inside useCallbacks
*
* Usage
* ```ts
* const [toggle, refCallback, myRef] = useRefWithCallback<HTMLSpanElement>();
* const onClick = useCallback(() => {
if (myRef.current) {
myRef.current.scrollIntoView({ behavior: "smooth" });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [toggle]);
return (<span ref={refCallback} />);
```
* #returns
*/
function useRefWithCallback<T extends HTMLSpanElement | HTMLDivElement | HTMLParagraphElement>(): [
boolean,
(node: any) => void,
RefObject<T>
] {
const ref = useRef<T | null>(null);
const [toggle, setToggle] = useState(false);
const refCallback = useCallback(node => {
ref.current = node;
setToggle(val => !val);
}, []);
return [toggle, refCallback, ref];
}
export default useRefWithCallback;
I've stopped using useRef and now just use useState once or twice:
const [myChart, setMyChart] = useState(null)
const [el, setEl] = useState(null)
useEffect(() => {
if (!el) {
return
}
// attach to element
const myChart = echarts.init(el)
setMyChart(myChart)
return () => {
myChart.dispose()
setMyChart(null)
}
}, [el])
useEffect(() => {
if (!myChart) {
return
}
// do things with attached object
myChart.setOption(... data ...)
}, [myChart, data])
return <div key='chart' ref={setEl} style={{ width: '100%', height: 1024 }} />
Useful for charting, auth and other non-react libraries, because it keeps an element ref and the initialized object around and can dispose of it directly as needed.
I'm now not sure why useRef exists in the first place...?

Resources