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
39,068
questions
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 ...
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 ...
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 ...
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 ...
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 = ...
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
...
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 ...
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 ...
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 ?
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 ...
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 ...
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?
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 ...
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 ...
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: &...
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 = () =&...
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?
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, ...
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?
...
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",
"...
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() {
...
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 ...
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 ...
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....
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 ...
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 ...
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 ...
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 &...
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, ...
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>
<...
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 = `...
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 ...
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, ...
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 ...
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('');
...
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 ...
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 ...
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 ...
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] ...
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 ...
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 => {
...
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 ...
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 ...
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'...
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.
...