score:3
are there any side effects to this? why would this work and not my original attempt?
no there are no side effects, that is the way to go in your situation. it didn't work in your case because you violated one of the rules of hooks:
don’t call hooks inside loops, conditions, or nested functions. instead, always use hooks at the top level of your react function, before any early returns. by following this rule, you ensure that hooks are called in the same order each time a component renders. that’s what allows react to correctly preserve the state of hooks between multiple usestate and useeffect calls. (if you’re curious, we’ll explain this in depth below.)
initially your usestate
calls themselves were wrapped inside a condition and that was a problem. that is not the case anymore with your newer approach.
score:0
if data can ever change....
the only thing you need to make sure you handle is that the data being passed down is not null
, but rather undefined
if it doesn't exist.
your useeffect
should have data
in the dependency array to re-render the component upon any change.
const calculate({data = 0}) => {
const [number, setnumber] = usestate(data);
useeffect(() => {
setnumber(data)
}, [data]);
}
score:8
you can use a ternary inside your usestate
hook and it will work fine. however, it is better to wrap it inside a function expression in the following manner.
const [number, setnumber] = usestate((data) => data === 'end' ? 5 : 0)
the function expression in above code snippet will be evaluated only once while setting the initial state. there is an upside to wrapping your ternary operator inside the function expression.
suppose that instead of data === 'end' ? 5 : 0
you want to use the results of an expensive computation to set the initial state, in such a case you can wrap it inside a function expression like:
const [number, setnumber] = usestate(() => expensivefunction())
this is better because () => expensivefunction()
will return a function which will only be evaluated once during the initial render. whereas if you don't wrap the expensivefunction
inside a function expression, it will be evaluated each time your component renders and block the execution of code until expensivefunction
returns a value.
this approach is also known as lazy initialization
.
Source: stackoverflow.com
Related Query
- React make useState initial value conditional
- React useState conditional initial value
- React - useState not setting initial value
- React useState value in Context API always use initial value instead of updated value
- React useState setting initial value has no effect
- How to set initial useState value in React based on props
- useState React hook always returning initial value
- Make conditional GraphQL request based on node type value in React component with Apollo Client
- React Hook useState value being reset to initial value
- Custom react hook with useState always resetting to its initial value
- react useState not working with new Date() as initial value
- React conditional update setState on basis of previous values, if state value is true make it false and vice versa
- React Functional Component - useState / useCallback - value changes back / reverts to initial value on submit
- How to type the initial state for react context when using useState as value
- React useState hooks initial value is null, after few seconds when got value then not updating where is use the value
- Setting the initial value of useState with async function using contextAPI and React
- Make React useEffect hook not run on initial render
- React useState hook event handler using initial state
- When to use useState initial value as function?
- useState with boolean value in react
- React useState does not seem to accept a default value here?
- React hooks useState setValue still rerender one more time when value is equal
- Clear Formik field with initial value React
- How to set initial state value for useState Hook in jest and enzyme?
- React Hooks Form Reset dont set Select to initial value
- React input text default value and onblur function make input text read only
- React - useState - update state: value vs function
- Render a div in React with an initial scrollTop value set
- React Hooks - useState value cannot change
- React useState giving previous state value always
More Query from same tag
- React js call api on page load
- Handle udefined or null in child component in reactjs
- testing simple functions in React
- Why do we need 2 entry points in server-side rendering?
- Error in requiring jquery
- How to add data to redux state array without any id in a reducer?
- How to use role based authentication on client side reactjs?
- Uncaught TypeError: Cannot read property 'touched' of undefined
- React: Trying to create separate folder for SVGs and import them into my components but unsure of how to import
- "Type is missing the following properties, context, setState" when having React Component as argument
- Redux failing to to pass store to React component
- How to implement a "render-as-you-fetch" pattern for routes in React
- react state changes in DOM but not in the logic
- ApolloConsumer and cache
- Retrieving data from csv file in react js
- javascript module import: import module what is based on react jsx syntax
- Add additional onClick() to Navigation Control
- React JS Server side issue - window not found
- Problem: Why is React updating my parent when i am setting state in children? Only happens to array
- React Function to Component and Setting State with Function Return
- React: TypeError: Cannot read properties of null (reading 'useContext') when trying to use react-bootstrap container
- Why is my media tag not working with my styled ocmponent?
- Validate Select in reactjs
- Rename a key value that is part of the React state
- Uncaught TypeError: node.scrollIntoView is not a function
- How to pass props to styled-component when using React.cloneElement
- Secure way to use dangerouslySetInnerHTML inside my react SharePoint Modern web part
- How do I change the size of the parent div without affecting the children nodes displayed?
- Difficulty trying to call a method from a parent to a child in React, with the child being an AntD form component
- My redirect is not working in class compoent?