1,787 questions
907
votes
21
answers
925k
views
The useState set method is not reflecting a change immediately
I am trying to learn hooks and the useState method has made me confused. I am assigning an initial value to a state in the form of an array. The set method in useState is not working for me, both with ...
172
votes
6
answers
121k
views
Why useEffect running twice and how to handle it well in React?
I have a counter and a console.log() in an useEffect to log every change in my state, but the useEffect is getting called two times on mount. I am using React 18. Here is a CodeSandbox of my project ...
886
votes
24
answers
1.2m
views
How to fix missing dependency warning when using useEffect React Hook
With React 16.8.6 (it was good on previous version 16.8.3), I get this error when I attempt to prevent an infinite loop on a fetch request:
./src/components/BusinessesList.js
Line 51: React Hook ...
593
votes
20
answers
916k
views
React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing
I was trying the useEffect example something like below:
useEffect(async () => {
try {
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
const json = ...
807
votes
26
answers
592k
views
useEffect() is called twice even if an empty array is used as an argument
I am writing code so that before the data is loaded from DB, it will show loading message, and then after it is loaded, render components with the loaded data. To do this, I am using both useState ...
285
votes
16
answers
163k
views
State not updating when using React state hook within setInterval
I'm trying out the new React Hooks and have a Clock component with a time value which is supposed to increase every second. However, the value does not increase beyond one.
function Clock() {
...
206
votes
19
answers
253k
views
Infinite loop in useEffect
I've been playing around with the new hook system in React 16.7-alpha and get stuck in an infinite loop in useEffect when the state I'm handling is an object or array.
First, I use useState and ...
372
votes
20
answers
364k
views
Make React useEffect hook not run on initial render
According to the docs:
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
We can use the new useEffect() hook to simulate ...
66
votes
5
answers
29k
views
Why is React useState with functional update form is needed?
I'm reading React Hook documentation about functional updates and see this quote:
The ”+” and ”-” buttons use the functional form, because the updated
value is based on the previous value
But I can'...
328
votes
23
answers
425k
views
How can I use multiple refs for an array of elements with hooks?
As far as I understood I can use refs for a single element like this:
const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, ...
422
votes
23
answers
426k
views
How to use `setState` callback on react hooks
React hooks introduces useState for setting component state. But how can I use hooks to replace the callback like below code:
setState(
{ name: "Michael" },
() => console.log(this.state)
);
I ...
351
votes
59
answers
1.1m
views
Invalid hook call. Hooks can only be called inside of the body of a function component
I want to show some records in a table using React but I got this error:
Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the ...
121
votes
7
answers
62k
views
Does React batch state update functions when using hooks?
For class components, this.setState calls batch if inside event handlers. But what happens if state is updated outside the event handler and using useState hook?
function Component() {
const [a, ...
27
votes
2
answers
13k
views
React useEffect in depth / use of useEffect?
I am trying to understand the useEffect hook in-depth.
I would like to know when to use which method and why?
useEffect with no second paraments
useEffect(()=>{})
useEffect with second paraments ...
392
votes
9
answers
611k
views
Push method in React Hooks (useState)?
How to push element inside useState array React hook?
Is that as an old method in react state? Or something new?
E.g. setState push example ?
121
votes
16
answers
170k
views
How can I use React hooks in React classic `class` component?
In this example, I have this react class:
class MyDiv extends React.component
constructor(){
this.state={sampleState:'hello world'}
}
render(){
return <div>{this.state....
594
votes
18
answers
766k
views
How to call loading function with React useEffect only once
The useEffect React hook will run the passed-in function on every change. This can be optimized to let it call only when the desired properties change.
What if I want to call an initialization ...
419
votes
17
answers
498k
views
How to compare oldValues and newValues on React Hooks useEffect?
Let's say I have 3 inputs: rate, sendAmount, and receiveAmount. I put that 3 inputs on useEffect diffing params. The rules are:
If sendAmount changed, I calculate receiveAmount = sendAmount * rate
If ...
116
votes
7
answers
130k
views
How to call an async function inside useEffect() in React?
I would like to call an async function and get the result for my UseEffect.
The fetch api examples I found on the internet are directly made in the useEffect function.
If my URL changes, I must patch ...
104
votes
9
answers
86k
views
Wrong React hooks behaviour with event listener
I'm playing around with React Hooks and am facing a problem.
It shows the wrong state when I'm trying to console log it using a button handled by event listener.
CodeSandbox: https://codesandbox.io/s/...
321
votes
19
answers
662k
views
React Hooks useState() with Object
What is the correct way of updating state, in a nested object, in React with Hooks?
export Example = () => {
const [exampleState, setExampleState] = useState(
{masterField: {
fieldOne: &...
134
votes
2
answers
180k
views
Is useState synchronous? [duplicate]
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....
257
votes
11
answers
455k
views
React hooks - right way to clear timeouts and intervals
I don't understand why is when I use setTimeout function my react component start to infinite console.log. Everything is working, but PC start to lag as hell.
Some people saying that function in ...
298
votes
6
answers
462k
views
Can I set state inside a useEffect hook
Lets say I have some state that is dependent on some other state (eg when A changes I want B to change).
Is it appropriate to create a hook that observes A and sets B inside the useEffect hook?
...
240
votes
12
answers
238k
views
With useEffect, how can I skip applying an effect upon the initial render?
With React's new Effect Hooks, I can tell React to skip applying an effect if certain values haven't changed between re-renders - Example from React's docs:
useEffect(() => {
document.title = `...
160
votes
10
answers
238k
views
How to register event with useEffect hooks?
I am following a Udemy course on how to register events with hooks, the instructor gave the below code:
const [userText, setUserText] = useState('');
const handleUserKeyPress = event => {
...
123
votes
9
answers
232k
views
Updating and merging state object using React useState() hook
I'm finding these two pieces of the React Hooks docs a little confusing. Which one is the best practice for updating a state object using the state hook?
Imagine a want to make the following state ...
284
votes
12
answers
148k
views
Accessing up-to-date state from within a callback
We use a third party library (over which there is limited control) that takes a callback as argument to a function. What is the correct way to provide that callback with the latest state? In class ...
238
votes
6
answers
132k
views
In useEffect, what's the difference between providing no dependency array and an empty one?
I gather that the useEffect Hook is run after every render, if provided with an empty dependency array:
useEffect(() => {
performSideEffect();
}, []);
But what's the difference between that, and ...
8
votes
3
answers
7k
views
React useState cause double rendering
Consider the canonical useState example:
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
console.log(count);
return (
<div ...
352
votes
11
answers
260k
views
componentDidMount equivalent on a React function/Hooks component?
Are there ways to simulate componentDidMount in React functional components via hooks?
206
votes
3
answers
229k
views
Understanding the React Hooks 'exhaustive-deps' lint rule
I'm having a hard time understanding the 'exhaustive-deps' lint rule.
I already read this post and this post but I could not find an answer.
Here is a simple React component with the lint issue:
const ...
440
votes
21
answers
480k
views
How to use componentWillMount() in React Hooks?
In the official docs of React it mentions -
If you’re familiar with React class lifecycle methods, you can think
of useEffect Hook as componentDidMount, componentDidUpdate, and
...
136
votes
10
answers
187k
views
Is it possible to share states between components using the useState() hook in React?
I was experimenting with the new Hook feature in React. Considering I have the following two components (using React Hooks) -
const HookComponent = () => {
const [username, setUsername] = ...
20
votes
2
answers
21k
views
React hooks useState setValue still rerender one more time when value is equal
I have sample code below:
function App() {
console.log("render");
const [val, setVal] = React.useState(0);
return (
<div className="App">
<h1>{val}</h1>
<...
173
votes
7
answers
213k
views
react useEffect comparing objects
I am using react useEffect hooks and checking if an object has changed and only then run the hook again.
My code looks like this.
const useExample = (apiOptions) => {
const [data, updateData] ...
125
votes
13
answers
309k
views
How do I update states `onChange` in an array of object in React Hooks
I have retrieved data stored using useState in an array of object, the data was then outputted into form fields. And now I want to be able to update the fields (state) as I type.
I have seen examples ...
243
votes
8
answers
497k
views
How to use callback with useState hook in react [duplicate]
I am using functional component with hooks. I need to update state in parent from a child. I am using a prop function in Parent.
All works fine except my prop function is getting the previous state ...
235
votes
8
answers
194k
views
Why is useState not triggering re-render?
I've initialized a state that is an array, and when I update it my component does not re-render. Here is a minimal proof-of-concept:
function App() {
const [numbers, setNumbers] = React.useState([0, ...
153
votes
29
answers
246k
views
How to use throttle or debounce with React Hook?
I'm trying to use the throttle method from lodash in a functional component, e.g.:
const App = () => {
const [value, setValue] = useState(0)
useEffect(throttle(() => console.log(value), 1000)...
88
votes
8
answers
153k
views
React-hooks. Can't perform a React state update on an unmounted component
I get this error:
Can't perform a React state update on an unmounted component. This is
a no-op, but it indicates a memory leak in your application. To fix,
cancel all subscriptions and ...
85
votes
5
answers
135k
views
Where can I make API call with hooks in react?
Basically we do API calls in componentDidMount() life cycle method in React class components like below
componentDidMount(){
//Here we do API call and do setState accordingly
}
...
77
votes
9
answers
32k
views
React useState hook event handler using initial state
I'm still getting my head around react hooks but struggling to see what I'm doing wrong here. I have a component for resizing panels, onmousedown of an edge I update a value on state then have an ...
20
votes
3
answers
48k
views
"Cannot use import statement outside a module" error when importing react-hook-mousetrap in Next.js
Trying out Next.js but I'm struggling with the following. Just tried to install react-hook-mousetrap and imported it like I normally would:
import useMousetrap from "react-hook-mousetrap";
...
262
votes
8
answers
171k
views
React.useState does not reload state from props
I'm expecting state to reload on props change, but this does not work and user variable is not updated on next useState call, what is wrong?
function Avatar(props) {
const [user, setUser] = React....
139
votes
5
answers
104k
views
is it possible to React.useState(() => {}) in React?
is it possible to use a function as my React Component's state ?
example code here:
// typescript
type OoopsFunction = () => void;
export function App() {
const [ooops, setOoops] = React....
0
votes
1
answer
4k
views
react useEffect hooks with axios cannot read property of undefined
This is based on exercise 2.14 of this course https://fullstackopen.com/en/part2/getting_data_from_server.
The user can select a country, then the weather information for that country's capital will ...
356
votes
5
answers
540k
views
Set types on useState React Hook with TypeScript
I'm migrating a React with TypeScript project to use hooks features (React v16.7.0-alpha), but I cannot figure out how to set typings of the destructured elements.
Here is an example:
interface IUser {...
315
votes
6
answers
163k
views
What's the difference between `useRef` and `createRef`?
I was going through the hooks documentation when I stumbled upon useRef.
Looking at their example…
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () =&...
236
votes
20
answers
452k
views
How can I force a component to re-render with hooks?
Considering below hooks example
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<...