Day 42-Custom Hooks,Refs and more State-Lesson 4

Photo by Joan Gamell on Unsplash

Day 42-Custom Hooks,Refs and more State-Lesson 4

Hi and welcome to Day 42 of my challenge!๐Ÿ’ชโค

ยท

2 min read

useState Summary

Let's summarize what we know about the useState Hook:

  • We use the useState Hook to create state variables and the corresponding update function (setState) .

  • State can be initialized with a simple value. But we can also set them up with a callback function, especially if the initial state involves computation, like fetching data from local storage. This process is known as lazy evaluation.

  • The callback function runs only during the initial rendering and must be pure and require no arguments.

  • To update state, we can either pass a new value directly to the setter function or use a callback function that computes the next state based on the current one.

  • It's essential to avoid mutating objects or arrays directly when updating state. Instead, create new objects or arrays with the desired changes and pass them to the setter function.

Introducing Another Hook: useRef

  • A ref, short for reference, is like a container where we can store data that we want to persist between renders.

  • When we use useRef, React provides an object with a mutable current property. We can write and read data into this property.

Uses of Refs:

  • Refs are handy for preserving data across renders, similar to state.

  • Two main use cases:

    • Storing variables that remain constant between renders, like previous state or setTimeout IDs.

    • Selecting and storing DOM elements for manipulation.

Refs vs. State:

  • Refs and state are similar in that they persist values across renders. However, they differ in re-render behavior.

  • Updating state triggers a re-render, while updating refs does not.

  • Use state for data that should trigger re-renders and refs for data that should only be remembered.

  • State is immutable, while refs are mutable.

  • State updates are asynchronous, meaning that we can't immediately use the new state value after updating it. On the contrary, updates with refs are synchronous. This means that we can read a new current property immediately after updating it.

  • Refs are typically reserved for data that doesn't directly contribute to the component's rendered output. They're commonly found in event handlers or effects, rather than within JSX so for non-rendered data. If the data you're working with affects the visual output of the component, it's often a sign that state should be used instead of a ref.

  • Avoid mutating or reading the current property in render logic to prevent side effects. Instead, perform mutations in a useEffect hook.

Thank you for reading...

To be continued...โœ

ย