Skip to content

Latest commit

 

History

History
44 lines (20 loc) · 2.17 KB

File metadata and controls

44 lines (20 loc) · 2.17 KB

Advanced State with Reducers

How can we ensure that an effect hook runs only once?

If we pass an empty array [] , it just renders the component only once like componentDidMount

Can useState() update more than one state variable at the same time?

You can have multiple states inside of a single component: call multiple times useState()

Is useState() synchronous?

no , useState() doesn't update value of the variable if called just after setting value.


  • State Hook : A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to function components. We'll learn other Hooks later.

  • Component Lifecycle : Every React Component has a lifecycle of its own, lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component's existence. ... A React Component can go through four stages of its life as follows


useReducer hook

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.

Ultimate Guide to useReducer

How does useReducer work?

  • useReducer is used to store and update states, just like the useState Hook. It accepts a reducer function as its first parameter and the initial state as the second.

  • useReducer returns an array that holds the current state value and a dispatch function, to which you can pass an action and later invoke. This is similar to the pattern Redux uses but with a few differences.