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.

react-hooks
Filter by
Sorted by
Tagged with
847 votes
22 answers
818k 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,583
839 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,433
674 votes
23 answers
450k 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,691
544 votes
18 answers
657k 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
538 votes
19 answers
762k 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,836
433 votes
21 answers
464k 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,074
409 votes
23 answers
397k 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.2k
393 votes
17 answers
436k 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,165
373 votes
9 answers
573k 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,644
353 votes
13 answers
488k 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,400
347 votes
20 answers
326k 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.3k
323 votes
11 answers
218k 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,383
316 votes
54 answers
929k 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,152
315 votes
5 answers
429k 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,304
310 votes
18 answers
621k 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,884
296 votes
6 answers
145k 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.4k
294 votes
3 answers
253k 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,624
290 votes
19 answers
360k 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
417k 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
264k 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
268 votes
15 answers
152k 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.3k
258 votes
11 answers
128k views

React hooks: accessing up-to-date state from within a callback

EDIT (22 June 2020): as this question has some renewed interest, I realise there may be a few points of confusion. So I would like to highlight: the example in the question is intended as a toy ...
rod's user avatar
  • 3,643
255 votes
11 answers
81k 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
158k 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,078
243 votes
11 answers
410k 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.2k
240 votes
9 answers
231k 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.3k
232 votes
8 answers
458k 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
343k 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
231 votes
9 answers
178k 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,735
221 votes
20 answers
423k 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
219 votes
11 answers
205k 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,636
219 votes
3 answers
155k 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,773
213 votes
5 answers
103k 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
202 votes
17 answers
225k 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,725
201 votes
12 answers
376k 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,173
187 votes
19 answers
470k 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,927
183 votes
2 answers
181k 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,474
166 votes
4 answers
113k 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,388
164 votes
7 answers
190k 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
157 votes
10 answers
217k 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
291k 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,053
156 votes
2 answers
143k 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
150 votes
11 answers
69k 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
148 votes
16 answers
237k views

How to change React-Hook-Form defaultValue with useEffect()?

I am creating a page for user to update personal data with React-Hook-Form. Once paged is loaded, I use useEffect to fetch the user's current personal data and set them into default value of the form. ...
theedchen's user avatar
  • 1,814

1
2 3 4 5
782