Questions tagged [react-hooks]

1

votes
1

answer
461

Views

How to fetch data by existing redux action with hooks?

I'm trying to understand React Hooks. What I want is to fetch data inside functional component by call redux action with useEffect hooks. I know that I can pass props to state like const [todoList] = useState(props.todoList) But what is the best practice to fetch data by existing redux actions? In...
Masaj
1

votes
2

answer
233

Views

Jest/Enzyme test throws error when using hooks

I have a simple React component that uses the useState hook. This component works correctly in the application, but my Jest test gives me the error 'Hooks can only be called inside the body of a function component'. As far as I can tell, I am calling useState correctly and, again, it works fine wh...
Jim Ade
1

votes
1

answer
96

Views

Mutating state from React's useState hook

Is it, and why is it a bad idea to mutate a state from React's new useState hook? I found no info on the topic. Consider following code: const [values, setValues] = useState({}) // doSomething can be called once, or multiple times per render const doSomething = (name, value) => { values[name] = valu...
Mykybo
1

votes
1

answer
55

Views

Is it better to pass context to a custom hook or call useContext inside the custom hook?

I have a growing number of custom hooks and many of them access the same react context via the useContext hook. In many components there is the need to use more than one of these custom hooks. Is it better to call useContext once per component and pass the context into my custom hooks or is it bett...
user1843640
1

votes
1

answer
171

Views

React hooks - state in useState() is not reset when route is changed

const Create = () => { console.log('rerender !!') const [parcelType, setParcelType] = useState('paper') console.log('parcelType =', parcelType) return ( setParcelType('plastic')}> Header ) } export default Create I want to change parcelType state to 'plastic' when click on Container in Create compon...
sarin udompanit
1

votes
2

answer
34

Views

React tree view app utilising Hooks (i.e. useCallback)

I am looking for opinions on my approach on building React tree view app utilising Hooks. Here's the code, utilising useCallback, React.memo and useState. Please note that there can be only one 1st level item opened at time, rest of the levels may have multiple items opened at once. Branch.js: impo...
user1346765
1

votes
2

answer
26

Views

Access the child state from the parent after click event from the parent

How to access the child state from the parent after triggering a click event in the parent ? I am using a modal component that's why the event is not triggering from the child component. const Parent = () => { ... return ( { // Get child state here to do some stuff with }} ... > ) } const Child = (...
Youssef
1

votes
1

answer
42

Views

useState does not set state when initalized by RouteProps

I have a component that uses useState. The state is initialized with a property from RouteComponentProps. It works when I type the url in the browsers addressbar, but not when URL is changed by a Link-tag. What's the difference? How can I set the state when url is changed by the Link-tag? Using the...
Erik Z
1

votes
2

answer
61

Views

React Hooks Mobx: invalid hook call. Hooks can only be called inside of the body of a function component

I am using React Hooks and when I wrap my component with observer from mobx, I am getting this error. What can be the problem? Is it possible to use mobx with React Hooks? import classnames from 'classnames'; import { observer } from 'mobx-react'; import React, { useState } from 'react'; import { Li...
drevival
0

votes
1

answer
14

Views

How to access a hook setter in an onClick function

I'm rewriting a class component to a functional component, but i can't figure out how to access a hook setter in an onClick function. I declare the hook as usual, which is a variable and a setter for accessing a username : export function Header(props: IHeaderProps) { const [username, setUsername] =...
melbil
0

votes
0

answer
11

Views

How can I add functionality to my addition, subtraction etc buttons on react js calculator

This is my first react project with hooks. I know the code is messy, but I just want to get the gist first, then organize the code later once it's complete. But I have a calculator app that I'm building and I need help with the state. I have two states, and I need help displaying the answer. The num...
weewee543
6

votes
1

answer
36

Views

Function called in setTimeout not using current React state

quick summary I'm trying to create a button that has both a regular click and a separate action that happens when a user clicks and holds it, similar to the back button in Chrome. The way I'm doing this involves a setTimeout() with a callback that checks for something in state. For some reason, the...
Zach
0

votes
0

answer
7

Views

React component: div with contenteditable using dangerouslySetInnerHTML jumping caret position

I'm currently building a component with a contenteditable div, using React. Since the content is generated by the user, I was trying to keep my component state in sync with its contents by using dangerouslySetInnerHTML. My other option was to update the innerHTML property directly. I thought it woul...
cbdev420
1

votes
1

answer
925

Views

React 16.7 TypeError: (0 , _react.useState) is not a function

Error: TypeError: (0 , _react.useState) is not a function My current react versions: 'react': '^16.7', 'react-dom': '^16.7', src/App.js: import {memo, useState} from 'react' export default memo(() => { useState(false) return 'OK' }) src/App.test.js: import React from 'react' import App from './App'...
Hemadri Dasari
1

votes
3

answer
211

Views

Is it possible to pass a React.hook to a function?

Can I pass React.hooks to a function and use it there? const [X, setX] = useState(''); function Y(useX){ useX('string'); } Y(setX)
Edgar Yedigaryan
1

votes
2

answer
26

Views

List Updates Incorrectly

A very simple list with inputs that are supposed to be addable and updatable. The problem occurs after I add one or more inputs and then try to type inside of one of the inputs - all inputs after the one being typed in disappear. It has something to do with memo-ing the Item component and I'm lookin...
Ivannnnn
0

votes
0

answer
17

Views

How to keep state updating to sessionStorage

In my app, I have a React component that renders a list of numbers and it also stores the sum of these numbers in sessionStorage. The component also has an input that adds a new number and updates the value stored in sessionStorage and a button in each number that if I click in it, removes the numbe...
Ramon
1

votes
2

answer
69

Views

What is the syntax for click events in React Hooks for passing arguments

This always worked great for me in React class components: let myValue: string = 'Hello World'; I found this syntax in the React Hooks documentation and I like it, but it does not always pass back a value: This syntax works, but is hard to type and looks messy: handleClick(myValue)}> This is yet ano...
Lambert
0

votes
0

answer
11

Views

Jest: setTimeout is being called too many times

I am testing a react component that uses setTimeout. The problem is that Jest is saying that setTimeout is called even though it clearly isn't. There is a setTimeout to remove something from the ui and another one to pause the timer when the mouse is hovering over the component. I tried adding a co...
RhinoBomb
3

votes
0

answer
24

Views

React efficiently update object in array with useState hook

I have a React component that renders a moderately large list of inputs (100+ items). It renders okay on my computer, but there's noticeable input lag on my phone. The React DevTools shows that the entire parent object is rerendering on every keypress. Is there a more efficient way to approach this?...
spiffytech
0

votes
0

answer
8

Views

How to use useRef hook to select next TextInput after pressing next keyboard button with redux-form

I know we can do this easily with react class method.because we have this.ref. but I am not sure how to do this with useRef hook in functional component. using tricks written here This is how I am trying to do this. ... const inputEl1 = useRef(null); const inputEl2 = useRef(null); return ( { inputEl...
shubham choudhary
0

votes
0

answer
5

Views

How to pass value to react-typescript context provider?

I am trying to pass value to a context provider to re-render children. My value is changed, but when I pass it to provider it doesn't set this value as current value. type LanguageContextType = { lang: string; changeLanguage(language: string): void; }; const LanguageContext = React.createContext({ l...
PrEto
0

votes
0

answer
16

Views

Should I include setState in useCallback's array of dependencies?

const [active, setActive] = useState(false); const onActiveChanged = useCallback( isActive => () => { // do something setActive(isActive); }, [setActive], // or just [] is okay? ); When using useState and useCallback (or useMemo) together, should I include setState in the array of dependencies?
alanhchoi
1

votes
0

answer
725

Views

React hooks useMemo/useCallback skip

How can I use useMemo's or useCallback's seconds argument to optimize based on a value inside the callback? const [s, setS] = useState({ page: { title: 'a', index: 3 } }); const getPage = data => data.page; const cb = useCallback(data => setS(data), [getPage(data)]); //...
norbertpy
1

votes
1

answer
264

Views

Trying to use React Hooks in ReactDOM.render. Is it right?

So i get dispatcher.useEffect is not a function react.development.js:1463 Uncaught TypeError: dispatcher.useEffect is not a function at useEffect (react.development.js:1463) at Preload (VM75697 Preload.js:40) at ProxyFacade (react-hot-loader.development.js:677) at mountIndeterminateComponent (react-...
chrisands
0

votes
2

answer
14

Views

How to target a specific item to toggleClick on using React Hooks?

I have a navbar component with that actual info being pulled in from a CMS. Some of the nav links have a dropdown component onclick, while others do not. I'm having a hard time figuring out how to target a specific menus index with React Hooks - currently onClick, it opens ALL the dropdown menus a...
geeberry
1

votes
2

answer
29

Views

How to iterate over different variables/states to create an object?

I need help iterating over variables/state elements to create an object. I am going to iterate over firstName state, lastName state, and many more states. The code is getting way too complicated. Was wondering if there is a proper way to build an object for a graphql call? or just a better way to bu...
Martin Fels
1

votes
2

answer
326

Views

Confusion about the inputs array of useEffect(React Hooks API)

Some React Hooks API like useEffect, useMemo, useCallback have a second parameter: an array of inputs: useEffect(didUpdate, inputs); As the official document said: @see Conditionally firing an effect That way an effect is always recreated if one of its inputs changes. every value referenced inside t...
李元秋
1

votes
0

answer
124

Views

Bug on integrating Material UI hooks and Apollo hooks

When using Material UI hooks (as its example shown here) with NextJS and react-apollo-hooks, received bug - TypeError: Cannot read property 'theme' of undefined at MyDocument.render (/material-ui/examples/nextjs-hooks-with-typescript/.next/server/static/development/pages/_document.js:156:38) Expect...
Ivan Wang
1

votes
2

answer
167

Views

Error when using useState in official example

This code came from here. import React from 'react'; import useState from 'react' let f = function() { const [count, setCount] = useState(0); return ( You clicked {count} times setCount(count + 1)}> Click me ); } export default f; Firstly, this line from that page... import React, { useState } from...
Ian Warburton
1

votes
1

answer
28

Views

Context.Provider rerendering to initial state when routing between pages

AppContextProvider wraps all components, private and not. Upon logging in, dispatch is called and the user info is updated and viewable in a private appbar. However, when navigating to another private route, the appbar goes back to the context default state. class App extends Component { render()...
Dan
8

votes
3

answer
1.9k

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 rendered twice, even though both calls to the state updater are happening in the same function. Here is...
jonhobbs
1

votes
0

answer
42

Views

React-Popper + custom Components using Hooks

I have a set of Components that should not use react-popper internally. I'm trying to have them be used as Reference with react-popper. I get that the solution is to use forwardRef, however, I spent hours trying to do it without great success. Is there any way someone could provide a sample for a si...
Mose
5

votes
1

answer
1.4k

Views

useState set method not reflecting change immediately

I am trying to learn hooks and the useState method has made me confused. I am assigning initial value to a state in the form of an array. The set method in useState is not working for me even with spread(...) or without spread operator. I have made an API on another pc which I am calling and fetchin...
Pranjal
1

votes
1

answer
34

Views

Creating a simple animation in React-Pose

I'm having trouble creating a simple animation in React-Pose. The two problems are 1) I can't get the animation to revert to the initial condition. The hovering variable is changing to false when the mouse leaves, but it the animation doesn't change back. 2) I can't manipulate the animation, I wante...
Jon
1

votes
1

answer
150

Views

How does useState() in react retrieve the correct state object and function for a functional component when using the state hook? [duplicate]

This question already has an answer here: How does React implement hooks so that they rely on call order 1 answer I am currently working on my understanding of the useState hook from react. What I would like to know is; when useState is called how is it able to correctly retrieve the state object a...
AdaRaider
1

votes
1

answer
86

Views

Hooks and immutable state

I am apologising in advance if this questions has already been answered before (and also for the long post, but I've tried to be as specific as I could be). But, the answers I found does not completely satisfy me. I want to use the new amazing React Hooks for my project. And for what I've been doing...
entiendoNull
1

votes
1

answer
89

Views

React Hooks FAQ: implementation of getderivedstatefromprops leads to rendering with incoherent state

IMHO The suggestion from React Hooks FAQ #getDerivedStateFromProps leads to one first rendering with a value of row that doesn't correspond to the value of isScrollingDown . As the call to setIsScrollingDown only schedules a new rendering and doesn't affect the current rendering, the latter will be...
bbo
1

votes
1

answer
180

Views

React useEffect hook not calling mocked function

Edit: This is now fixed, but I'm not sure why. Please review this original post and my additional edit below, I would appreciate feedback as to why this is now working. So I am new to React hooks. I'm using a useEffect() hook in a component, and that hook calls a function, searchForVideos() from my...
user2223059
1

votes
0

answer
113

Views

Using useReducer results in Invariant Violation: Hooks can only be called inside the body of a function component

I'm having some issues with latest React for React Native all development, since React introduced hooks I'm trying to play around with it, but to no avail. I'm having a Screen for RN to do some splash screen animations and it does not work with latest React, always giving me the above error. (it is...
Patryk

View additional questions