Questions tagged [react-hooks]

React Hooks are a feature that allows developers to use state(s) and other React component lifecycle features without writing a class-based component.

Filter by
Sorted by
Tagged with
852 votes
22 answers
825k 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 ...
Pranjal's user avatar
  • 8,633
841 votes
23 answers
1.1m 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 ...
russ's user avatar
  • 8,453
684 votes
23 answers
459k views

React Hooks: 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 ...
J.Ko's user avatar
  • 7,801
547 votes
18 answers
663k 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 ...
Dávid Molnár's user avatar
541 votes
20 answers
770k 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 = ...
RedPandaz's user avatar
  • 5,866
433 votes
21 answers
466k 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 ...
Abrar's user avatar
  • 7,084
409 votes
23 answers
399k 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 ...
Joey Yi Zhao's user avatar
  • 40.4k
394 votes
17 answers
440k 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 ...
Erwin Zhang's user avatar
  • 4,175
373 votes
9 answers
576k 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 ?
Milos N.'s user avatar
  • 4,642
355 votes
13 answers
496k views

Attempted import error: 'useHistory' is not exported from 'react-router-dom'

useHistory giving this error: Failed to compile ./src/pages/UserForm/_UserForm.js Attempted import error: 'useHistory' is not exported from 'react-router-dom'. This error occurred during the build ...
Nafeo Alam's user avatar
  • 4,416
351 votes
20 answers
329k 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 ...
Yangshun Tay's user avatar
  • 51.5k
324 votes
11 answers
220k views

componentDidMount equivalent on a React function/Hooks component?

Are there ways to simulate componentDidMount in React functional components via hooks?
jeyko's user avatar
  • 3,393
318 votes
5 answers
437k 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 ...
Hassen's user avatar
  • 7,334
318 votes
55 answers
940k 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 ...
lwin's user avatar
  • 4,172
311 votes
19 answers
623k 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: &...
isaacsultan's user avatar
  • 3,904
299 votes
6 answers
146k 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 = () =&...
Rico Kahler's user avatar
  • 18.5k
295 votes
3 answers
255k views

In general is it better to use one or many useEffect hooks in a single component? [closed]

I have some side effects to apply in my react component and want to know how to organize them: as a single useEffect or several useEffects Which is better in terms of performance and architecture?
Vadim's user avatar
  • 3,634
291 votes
20 answers
365k 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, ...
devserkan's user avatar
  • 17.3k
283 votes
6 answers
420k 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? ...
Dan Ruswick's user avatar
  • 3,070
272 votes
36 answers
266k views

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

I'm trying to use react hooks for a simple problem const [personState,setPersonState] = useState({ DefinedObject }); with following dependencies. "dependencies": { "react": "^16.8.6", "...
Bishnu's user avatar
  • 2,794
270 votes
15 answers
153k 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() { ...
Yangshun Tay's user avatar
  • 51.5k
258 votes
11 answers
130k 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 ...
rod's user avatar
  • 3,653
256 votes
11 answers
83k views

Determine which dependency array variable caused useEffect hook to fire

Is there an easy way to determine which variable in a useEffect's dependency array triggers a function re-fire? Simply logging out each variable can be misleading, if a is a function and b is an ...
Cumulo Nimbus's user avatar
246 votes
8 answers
159k 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....
vitalyster's user avatar
  • 5,103
243 votes
11 answers
413k 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 ...
ZiiMakc's user avatar
  • 34.3k
241 votes
9 answers
232k views

Multiple calls to state updater from useState in component causes multiple re-renders

I'm trying React hooks for the first time and all seemed good until I realised that when I get data and update two different state variables (data and loading flag), my component (a data table) is ...
jonhobbs's user avatar
  • 27.4k
232 votes
8 answers
179k 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, ...
Ryan Z's user avatar
  • 2,746
232 votes
8 answers
461k 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 ...
Atul's user avatar
  • 3,163
232 votes
14 answers
344k views

What is useState() in React?

I am currently learning hooks concept in React and trying to understand below example. import { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call &...
Hemadri Dasari's user avatar
222 votes
20 answers
426k views

How can I force a component to re-render with hooks in React?

Considering below hooks example import { useState } from 'react'; function Example() { const [count, setCount] = useState(0); return ( <div> <...
Hemadri Dasari's user avatar
221 votes
11 answers
207k 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 = `...
uturnr's user avatar
  • 2,656
220 votes
4 answers
156k views

useMemo vs. useEffect + useState

Are there any benefits in using useMemo (e.g. for an intensive function call) instead of using a combination of useEffect and useState? Here are two custom hooks that work exactly the same on first ...
Bennett Dams's user avatar
  • 6,783
217 votes
5 answers
105k 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, ...
Paul Razvan Berg's user avatar
203 votes
12 answers
380k views

react hooks useEffect() cleanup for only componentWillUnmount?

Let me explain the result of this code for asking my issue easily. const ForExample = () => { const [name, setName] = useState(''); const [username, setUsername] = useState(''); ...
koo's user avatar
  • 4,193
202 votes
17 answers
227k 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 ...
WhiteFluffy's user avatar
  • 4,745
188 votes
19 answers
472k views

React useEffect causing: Can't perform a React state update on an unmounted component

When fetching data I'm getting: Can't perform a React state update on an unmounted component. The app still works, but react is suggesting I might be causing a memory leak. This is a no-op, but it ...
Ryan Sam's user avatar
  • 2,947
184 votes
2 answers
184k 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 ...
Logan Wlv's user avatar
  • 3,504
167 votes
4 answers
114k views

What typescript type do I use with useRef() hook when setting current manually?

How can I use a React ref as a mutable instance, with Typescript? The current property appears to be typed as read-only. I am using React + Typescript to develop a library that interacts with input ...
JPollock's user avatar
  • 3,398
166 votes
7 answers
192k 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] ...
peter flanagan's user avatar
159 votes
19 answers
100k views

Line 0: Parsing error: Cannot read property 'map' of undefined

Currently starting up the server on my client side, the error above is what I have been getting. I am using TypeScript, ReactJS, ESLint. I can't seem to go forward since this error has been haunting ...
Jon Hernandez's user avatar
158 votes
10 answers
219k 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 => { ...
Isaac's user avatar
  • 12.6k
157 votes
7 answers
293k views

Handle an input with React hooks

I found that there are several ways to handle user's text input with hooks. What is more preferable or proper way to handle an input with hooks? Which would you use? 1) The simplest hook to handle ...
ligowsky's user avatar
  • 2,083
157 votes
2 answers
144k views

How to change the value of a Context with useContext?

Using the useContext hook with React 16.8+ works well. You can create a component, use the hook, and utilize the context values without any issues. What I'm not certain about is how to apply changes ...
Randy Burgess's user avatar
151 votes
13 answers
270k views

Uncaught Invariant Violation: Rendered more hooks than during the previous render

I have a component that looks like this (very simplified version): const component = (props: PropTypes) => { const [allResultsVisible, setAllResultsVisible] = useState(false); const ...
timothym's user avatar
  • 3,035
150 votes
11 answers
70k views

React: useState or useRef?

I am reading about React useState() and useRef() at "Hooks FAQ" and I got confused about some of the use cases that seem to have a solution with useRef and useState at the same time, and I'...
Haim763's user avatar
  • 1,584

1
2 3 4 5
782