Questions tagged [react-hooks]

1

votes
1

answer
119

Views

Set model state with React Hooks in form inputs

How do I change the state of a model using the built-in setState() function in React Hooks for form inputs? For example how do bind setFirstName() with onChange in the input field? import React, { useState } from 'react'; const Demo = () => { const [ firstName, setFirstName ] = useState(''); return...
Pranay Aryal
1

votes
3

answer
141

Views

When to use native React.useReducer Hook and how it differentiate from Redux

So, Hooks are available from React 16.8. From their documentation, Hooks come as a replacer of state in functional components. The basic hooks are: useState, useEffect, useContext, but there are also some additional hooks, one of them being useReducer, and it looks like it uses the same action-dispa...
Relu Mesaros
1

votes
3

answer
52

Views

Using Dynamic Var with `Set` State in React Hooks?

This is a pretty common pattern in React components: handleTextFieldChange(event) { const name = event.currentTarget.name; this.setState({[name]: event.currentTarget.value}) } What Javascript syntax could be used to do the same with React hooks? i.e. something possibly along the lines of: handleText...
VikR
3

votes
0

answer
22

Views

React hook rendering an extra time

My code is causing an unexpected amount of re-renders. function App() { const [isOn, setIsOn] = useState(false) const [timer, setTimer] = useState(0) console.log('re-rendered', timer) useEffect(() => { let interval if (isOn) { interval = setInterval(() => setTimer(timer + 1), 1000) } return () =...
Adam Hartleb
1

votes
1

answer
216

Views

react-hooks: skip first run in useEffect [duplicate]

This question already has an answer here: With useEffect, how can I skip applying an effect upon the initial render? 1 answer How I can skip first run in useEffect hook. useEffect(() => { const first = // ??? if (first) { // skip } else { // run main code } }, [id]);
seyed
1

votes
4

answer
103

Views

componentDidMount equivalent on a React function/Hooks component?

Are there ways to simulate componentDidMount in React functional components possibly via hooks?
jeyko
1

votes
1

answer
44

Views

Successfully firing two useReducer hooks in a row

I have a useReducer hook const [state, dispatch] = React.useReducer(reducer, initialState); It has two cases that set a string on state function reducer(state, action) { switch (action.type) { case 'ONE': return { a: action.payload }; case 'TWO': return { b: action.payload }; default: throw new Erro...
Josh Pittman
1

votes
1

answer
29

Views

How to early exit useEffect hook?

In the docs it says that we should only call hooks at the top level of our components. Due to the API of useEffect, return is already reserved for the cleanup which made me wonder how I could early exit a useEffect hook to prevent deeply nesting my if statements. // instead of React.useEffect(() =>...
MrKey
1

votes
1

answer
23

Views

React w/hooks: prevent re-rendering component with a function as prop

Let's say I have: const AddItemButton = React.memo(({ onClick }) => { // Goal is to make sure this gets printed only once console.error('Button Rendered!'); return Add Item; }); const App = () => { const [items, setItems] = useState([]); const addItem = () => { setItems(items.concat(Math.random()));...
lxe
1

votes
0

answer
7

Views

Passing imported style object into a custom hook does not work as expected

I am trying to create a custom hook which will handle some merging of Aphrodite (https://github.com/Khan/aphrodite) styles for us, but I'm getting some unusual behaviour with the styles object being passed in. Here's my hook: (the plan was to compose with useMemo which is why it's a hook at all) imp...
Ben Slinger
0

votes
0

answer
4

Views

How to sync props to state using React hook : setState()

I am trying to set the state using React hook setState() using the props the component receive. I've tried using the below code: import React,{useState , useEffect} from 'react'; const Persons = (props) => { // console.log(props.name); const [nameState , setNameState] = useState(props) console.log(...
METALHEAD
0

votes
0

answer
11

Views

React-devtools for hooks?

I use the react-devtools Chrome extension. When I set state using hooks (useState) to set an object in state, the actual setting of state seems to work fine. In devtools however, that state object shows that the Hooks > State has content ({...}), it also implies that the content is accessible . W...
stever
1

votes
1

answer
138

Views

Using React Hooks useReducer, how can I update an object by ID efficiently?

I have a StackBlitz that you can fork, I found a similar answer but I'm having trouble applying it to my example, I think it's because I have an array of objects. I have the code working but it's very verbose, and I would like something easier to read that others who use Redux will recognize. const...
Eric Bishard
1

votes
1

answer
128

Views

What is the intension of using React's useCallback hook in place of useEffect?

I'm trying to understand what the use case is for using React's useCallback hook in place of the useEffect hook. They both appear to act as a listener for state changes of their inputs (examples taken from the React Docs): useEffect( () => { const subscription = props.source.subscribe(); return () =...
Don Brody
0

votes
0

answer
5

Views

Errors while using React Hooks with Electron JS and react-data-grid

I am trying to integrate react data grid with electron js and I am facing issues while using "useState". The console asks me to add error boundaries and adding that didn't help too. I searched for similar problems in stackoverflow and made sure that the react is upgraded to the latest version for us...
sdg
0

votes
0

answer
13

Views

ReactJS - Prevent initial animation of modal with react hooks

I built simple Modal component which will slide from bottom when opened. Animations are working fine when Modal trigger button clicked and backdrop clicked. But i am seeing slide-down animation at initial render of page. How can i prevent initial animation ?? I am specifically looking how to solve w...
REDDY PRASAD
1

votes
3

answer
84

Views

Referencing outdated state in React useEffect hook

I want to save state to localStorage when a component is unmounted. This used to work in componentWillUnmount. I tried to do the same with the useEffect hook, but it seems state is not correct in the return function of useEffect. Why is that? How can I save state without using a class? Here is a dum...
r03
2

votes
1

answer
17

Views

What's useEffect execution order and its internal clean-up logic in react hooks?

According to react document, useEffect will trigger clean-up logic before it re-run useEffect part. If your effect returns a function, React will run it when it is time to clean up... There is no special code for handling updates because useEffect handles them by default. It cleans up the previous e...
hijiangtao
3

votes
2

answer
383

Views

React Hooks can only be called inside the body of a function component

How do I trigger useEffect() on a button click, rather than on rendering the component? When I use it inside a function like this, I get an error stating: Hooks can only be called inside the body of a function component function App() { function buttonClicked() { useEffect(() => { // Fetch from A...
Alan
3

votes
2

answer
526

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 = await response.json(); setPosts(json.data.children.map(it => it.data)); } catch (e) { console.error(e); } }, []); a...
RedPandaz
6

votes
3

answer
293

Views

React 16.7 Hooks : `react.useState` is not a function

I am trying functional components with hooks of react 16.7,there is an error: src/components/Footer/index.js function Footer() { const [selectedTab, setSelectedTab] = useState('redTab'); const [hidden, setHidden] = useState(false); const [fullScreen, setFullScreen] = useState(false); //... } package...
zwl1619
3

votes
3

answer
93

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] = useState('Abrar'); const [count, setState] = useState(); const handleChange = (e) => { setUsername(e.target.val...
Abrar
2

votes
1

answer
82

Views

What useCallback do in React?

As sad in docs its: Returns a memoized callback. Pass an inline callback and an array of inputs. useCallback will return a memoized version of the callback that only changes if one of the inputs has changed. This is useful when passing callbacks to optimized child components that rely on reference e...
RTW TMI
2

votes
1

answer
346

Views

“Cannot import useState because there is no useState export in react” (Flow with React Hooks)

I hope I'm not repeating a question. I've seen this one: TypeError dispatcher.useState is not a function when using React Hooks, however my App runs fine, it is only an error in Flow: Cannot import `useState` because there is no `useState` export in `react`. 4| import { useState } from 'react'; I am...
P Fuster
2

votes
3

answer
120

Views

Use React hook to implement a self-increment counter [duplicate]

This question already has an answer here: State not updating when using React state hook within setInterval 1 answer The code is here: https://codesandbox.io/s/nw4jym4n0 export default ({ name }: Props) => { const [counter, setCounter] = useState(0); useEffect(() => { const interval = setInterval((...
PeiSong
2

votes
1

answer
64

Views

How to focus something on next render with React Hooks

I'm playing with hooks, and I'm trying to do the following: import React, { useState, useRef } from 'react'; const EditableField = () => { const [isEditing, setEditing] = useState(false); const inputRef = useRef(); const toggleEditing = () => { setEditing(!isEditing); if (isEditing) { inputRef.curre...
Kris Selbekk
4

votes
5

answer
277

Views

React Hooks - Making an Ajax request

I have just began playing around with React hooks and am wondering how an A request should look? I have tried many attempts, but am unable to get it to work, and also don't really know the best way to implement it. Below is my latest attempt: import React, { useState, useEffect } from 'react'; const...
peter flanagan
6

votes
1

answer
123

Views

React Hooks and Component Lifecycle Equivalent

What are the equivalents of the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle hooks using React hooks like useEffect?
Yangshun Tay
4

votes
1

answer
89

Views

Does React batches 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, setA] = useState('a'); const [b, setB] = useState('b'); function handleClick() { Promise.resolve().then...
vadirn
3

votes
1

answer
35

Views

How to package my React hook effects for others to re-use?

I'm want to create several open-source React effects for react hooks. For e.g., an effect that checks and updates the user token balance. The question is: How to pack the effect and create a module, so it will be easy for others to use? How are they going to import and use the effect? There is any b...
Aminadav Glickshtein
3

votes
2

answer
196

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 initiate it with an empty object like this: const [obj, setObj] = useState({}); Then, in useEffect, I use...
Tobias Haugen
3

votes
3

answer
86

Views

React functional component reinitialises local functions and variables on re render (React Hooks)

So I have started using React hooks now. I have been experimenting with the API for some time now. i really like the idea of bringing the state to functional components. but there is this one thing which keeps on bothering me and it doesn't feel right in the gut when i am trying to use it. I tried p...
hannad rehman
2

votes
2

answer
159

Views

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

Considering below hooks example import { useState } from 'react'; function Example() { const [count, setCount] = useState(0); return ( You clicked {count} times setCount(count + 1)}> Click me ); } Basically we use this.forceUpdate() method to force the component to re-render immediately in React cl...
Hemadri Dasari
2

votes
1

answer
103

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 = `You clicked ${count} times`; }, [count]); // Only re-run the effect if count changes But the example above...
uturnr
2

votes
2

answer
101

Views

Can I replace context with hooks?

Is there a way with new react hooks API to replace a context data fetch? If you need to load user profile and use it almost everywhere, first you create context and export it: export const ProfileContext = React.createContext() Then you import in top component, load data and use provider, like this:...
RTW TMI
2

votes
1

answer
72

Views

React hook useEffect runs continuously forever/infinite loop

I'm trying out the new React Hooks's useEffect API and it seems to keep running forever, in an infinite loop! I only want the callback in useEffect to run once. Here's my code for reference: Click "Run code snippet" to see the "Run useEffect" string is being printed to the console infinitely. functi...
Yangshun Tay
3

votes
1

answer
170

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 componentDidUpdate(), but it seems like useEffect() is being ran after every render, even the first time. How do...
Yangshun Tay
1

votes
4

answer
237

Views

React hooks: are they useful for shared state management, like e.g. Redux?

There is a hype about React hooks. Too much information and I still don't know: does the advent of hooks mean that libs like Redux can be thrown to garbage? So far, what I understood is hooks are good for stateful functional components, what about shared state?
Nurbol Alpysbayev
1

votes
2

answer
172

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 } But after hooks are introduced in React v16.7.0, there are no more class components. My query is, where exactly do we need...
Hemadri Dasari
1

votes
2

answer
109

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 receiveAmount changed, I calculate sendAmount = receiveAmount / rate If rate changed, I calculate re...
rwinzhang

View additional questions