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,123
questions
861
votes
22
answers
852k
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 ...
856
votes
23
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 ...
718
votes
24
answers
495k
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 ...
560
votes
17
answers
688k
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 ...
549
votes
20
answers
808k
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 = ...
435
votes
21
answers
470k
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
...
412
votes
23
answers
407k
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 ...
399
votes
17
answers
454k
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 ...
381
votes
9
answers
588k
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 ?
367
votes
13
answers
520k
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 ...
358
votes
20
answers
338k
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 ...
334
votes
11
answers
231k
views
componentDidMount equivalent on a React function/Hooks component?
Are there ways to simulate componentDidMount in React functional components via hooks?
329
votes
56
answers
978k
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 ...
325
votes
5
answers
464k
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 ...
313
votes
19
answers
634k
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: &...
304
votes
6
answers
151k
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 = () =&...
302
votes
20
answers
380k
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, ...
301
votes
3
answers
263k
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?
284
votes
6
answers
431k
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?
...
275
votes
15
answers
156k
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() {
...
273
votes
36
answers
272k
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",
"...
269
votes
11
answers
89k
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 ...
261
votes
11
answers
134k
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 ...
250
votes
8
answers
163k
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....
246
votes
11
answers
424k
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 ...
243
votes
9
answers
235k
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 ...
236
votes
8
answers
471k
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 ...
233
votes
8
answers
184k
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, ...
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 &...
227
votes
20
answers
434k
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>
<...
226
votes
11
answers
214k
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 = `...
225
votes
4
answers
164k
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 ...
222
votes
6
answers
111k
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, ...
207
votes
12
answers
394k
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('');
...
203
votes
18
answers
233k
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 ...
189
votes
19
answers
479k
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 ...
189
votes
2
answers
194k
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 ...
170
votes
4
answers
119k
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 ...
170
votes
7
answers
198k
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] ...
160
votes
10
answers
224k
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 => {
...
159
votes
19
answers
102k
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
7
answers
298k
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 ...
157
votes
13
answers
291k
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 ...
157
votes
2
answers
148k
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 ...
156
votes
6
answers
117k
views
When to use useCallback, useMemo and useEffect?
What is the main difference between useCallback, useMemo and useEffect?
Give examples of when to use each of them.