#useRef
Explore tagged Tumblr posts
Text
Mastering the useRef Hook in React: A Quick and Informative Guide
React useRef Hook is a powerful tool for managing and interacting with DOM elements and persisting mutable values across renders. Unlike state, updating a useRef value doesn’t trigger a re-render, making it ideal for situations where you need to maintain values without causing unnecessary updates to your component.
What is useRef?
The useRef Hook creates a reference to a value or a DOM element. The reference persists across renders but doesn't cause the component to re-render when updated. It is typically used for two main purposes:
Accessing DOM Elements:You can directly interact with a DOM element without causing a re-render.
Persisting Mutable Values:Use it to store values that need to persist between renders but shouldn't trigger a re-render.
Use Case 1: Accessing DOM Elements
One common use of useRef is to interact with DOM elements. For example, you can create a ref for an input field and then programmatically focus it. When the button is clicked, the input field gains focus, all without causing a re-render.
Use Case 2: Persisting Values Across Renders
You can also use useRef to store values that need to persist across renders without triggering re-renders, such as keeping track of previous values or timers. The timer reference is maintained across renders without causing a re-render every time the timer updates.
When to Use useRef vs. useState?
useState: Use when you need to trigger a re-render on state changes.
useRef: Use when you want to persist values across renders without triggering re-renders, especially for DOM interactions.
How Memetic Solutions Leverages useRef for Superior Products?
At Memetic Solutions, we harness the power of useRef to create seamless, high-performance web applications. By avoiding unnecessary re-renders, we ensure our clients' products are efficient, responsive, and user-friendly. Whether it's managing timers, working with animations, or interacting with complex UI elements, useRef allows us to build intuitive, real-time interactions without performance lags, enabling us to deliver superior user experiences. Our ability to implement modern React technologies like useRef guarantees that our clients always receive top-tier solutions tailored to their needs.
#useRef#ReactJS#ReactHooks#JavaScriptDevelopment#WebDevelopment#FrontendDevelopment#MemeticSolutions#ReactTips#ReactBestPractices#CodingWithReact#WebAppDevelopment#ReactGuide#JavaScriptTips#DeveloperTool#ReactTutorial
0 notes
Text
React Lifecycle Methods with Hooks
As a developer working with React, you may be familiar with the term “lifecycle methods.” These methods are a set of functions that are called at specific times during a component‘s life cycle. They allow you to perform actions at specific points in time, such as when a component is first created or when it is about to be removed from the DOM. what you will learn in this…
View On WordPress
#component lifecycle react#componentdidmount#componentdidmount functional component#componentdidmount in functional component#componentwillmount#componentwillunmount#react functional component lifecycle#react hook lifecycle#react lifecycle#useContext#useEffect#useeffect componentdidmount#useReducer#useRef#useState
1 note
·
View note
Text
Hooked on React: Mastering the Art of Hooks
Hey Guys, It's been a while since I posted, but here I am with my new blog on React hooks. Take a look at it and don't hesitate to share your thoughts!
Have you ever been asked by a client to change a functional component into a class component where all the UI and business logic are the same but the only difference is that you need to add some state? If so, then most developers will sympathize. But now we don’t have to do that because, as of React 16.8, we can now manage states in functional components too! Here we will learn about React…
View On WordPress
#All you need to know about React hooks#Common Used React Hooks#Custom Hooks#Hooked on React: Mastering the Art of Hooks#hooks#React hooks#React JS#Rules of React Hooks#Testing React Hooks#useCallback#useContext#useEffect#useLayoutEffect#useMemo#useReducer#useRef#useState#Working with React Hooks
1 note
·
View note
Text
14/07/2023 || Day 51
React & Weather App Log # 2
React:
Decided to skip on the video tutorials today and instead focused on Hooks and Refs, and oh god that hurt my brain. From my understanding, Hooks are used to keep the state of a functional component, letting them have states to begin with. Along with Refs, we can update states/variables when appropriate (i.e. a user types in their name, we can now store that name in a variable). One thing that I struggled with was understanding what the code for useState in the documentation meant, but after watching a video I learned that useState returns an array in which the first element is the variable you want to keep track of, and the second element is the method used to set the value of the variable ( i.e. const [userAnswer, setUserAnswer] = useState(null) ). So, when you want to update userAnswer, you call setUserAnswer() and do the logic inside this method. To get used to using both Hooks and Refs, I continued a bit with my Weather App.
Weather App:
Like I said, I mainly wanted to practice using Hooks and Refs. One thing that I need in my weather app is for the user to type in their city (or any city), so this was the perfect time to use Hooks and Refs. I have the app set up this way: if the variable city is undefined (i.e. the user hasn't entered the city they want to get the weather for), the React component for entering the city will show up (which I called GetCity). Otherwise, the component holding the weather info will display (which I called Header).
To get the user input from the input element in my GetCity component, I ended up using the useRef method (though I think I can also use useState), and actually ended up passing this variable to the parent component, which will then pass it down to the Header component that will display the weather and such.
Now that the user typed in the city, I need to make an API call to get the weather. I'm doing this with the OpenWeather API, but first I actually need to get some location information from another API they have; their Geocoding API. With this, I can send in my city name and get back information such as the longitude and the latitude of the city, which I'll need to make the API call to get the weather. So far, I have it where I can get the longitude and latitude, but I have yet to store the values and make the 2nd API call. It'll be a few days before I get this working, but here's a little video of it "working" so far (you can see it works from the console on the right). The first screen is the GetCity component, as the user hasn't entered a city yet, and once they do and click the button, the parent component now has the city name and passes it down to the Header component:
20 notes
·
View notes
Text
Q&A tag game
Tagged by @verai-marcel. Thanks!
Last Song: Pacific Coast Highway by Fukkk Offf
Currently Watching: Pluto
Sweet/Savory/Spicy: Savory 😋
Relationship Status: Taken
Current Obsession: I am also playing Hades but I am so bad at it, man. What the hell am I doing.
Last Thing I Googled: useRef react hook
Tagging @rivetingrosie4, @annalikespoetry, and @confuse-and-lonely 💖
6 notes
·
View notes
Text
Roadmap for react developer
Roadmap for React Developers
Becoming a proficient React developer involves a structured approach to learning various concepts, tools, and libraries. Below is a comprehensive roadmap that outlines the essential steps for both beginners and those looking to advance their skills in React.
1. Foundations Before React
HTML/CSS: Understanding the structure and styling of web pages.
JavaScript: Proficiency in ES6 features such as arrow functions, destructuring, and modules.
Version Control: Familiarity with Git for managing code changes.
2. Core React Concepts
Components: Learn to create functional components using JSX.
Props and State: Understand how to pass data between components and manage component state.
Conditional Rendering: Master rendering different components based on conditions.
3. Core Hooks
useState: Manage state in functional components.
useEffect: Handle side effects like data fetching or subscriptions.
useRef: Access DOM elements directly without causing re-renders.
useContext: Share state across components without prop drilling.
4. Intermediate Concepts
Styling: Use CSS frameworks like TailwindCSS or libraries like styled-components for styling your applications.
Routing: Implement routing in your applications using React Router for multi-page navigation.
Forms Management: Utilize libraries like React Hook Form for handling form inputs and validation.
5. Advanced Topics
State Management: Explore state management solutions such as Redux or Zustand for complex applications.
Data Fetching: Use libraries like TanStack Query for efficient data fetching and caching strategies.
Server-Side Rendering (SSR): Learn about frameworks like Next.js to build full-stack applications with server-rendered pages.
6. Building Projects
Start with simple projects to apply what you've learned, gradually increasing complexity as you gain confidence.
Consider contributing to open-source projects or building portfolio projects that showcase your skills.
7. Continuous Learning
Stay updated with the latest features and best practices in the React ecosystem by following community resources, blogs, and tutorials.
Engage with the community through forums, Discord channels, or local meetups.
By following this roadmap, aspiring React developers can systematically build their skills and knowledge, making them well-equipped to tackle real-world projects and job opportunities in the field of web development[1][2][3].
0 notes
Text
Combining the Power of D3 JS with react for superior performance
Getting with the Introduction of D3 JS and React JS
Certainly, this term might be new to you, "D3," but it is the most flexible and powerful JavaScript library that is used by most data scientists and developers as well to create interactive and dynamic visualizations. Yes, you have read it right! Moreover, D3 has a very flexible path that allows developers to create or build rich and interactive visualization, which includes animation as well! But are you still wondering about its' popularity? Over the past few decades, D3 JS has been used for data visualization, and it is one of the top 100 most-starred repositories on GitHub. Most companies use D3JS, like Coursera, Accenture, and much more. But what if D3 JS gets blended with React? Ever wondered? In this blog, we will look into the combination of D3 JS and React, and we will also understand how to implement D3 in React JS. So, without any further delay, let's jump into this blog to learn more!
Exploring the Basis of React with D3
When we talk about this perfect duo combination of React and D3 JS, they both can be used for creating interactive visualization. React is the most popular open-source JavaScript library for building all types of user interfaces for native and web application platforms. And on the other hand, when we talk about D3 JS, it is used by most data scientists for adding visual representation to their development process.
But when this gets combined with D3 JS and React, it has the ability to build all the interactive and complex UIs that require minimal coding, which is a major advantage as well. And this is very useful for building all the data visualization, where developers can create several other components according to their ideas. Also, D3 JS has an API that is powerful and more flexible, which makes it an ideal choice for all the developers who want to create customization visualizations. So, with the help of React and d3 JS, any developer can create more engaging data presentations.
A Complete Relic on How to Implement D3 in React JS
When it comes to implementing or integrating D3JS in React, the first step is to create a React application, which can be done by using npx. The second step is to install the D3 JS in the existing application, and once this is done, the next step is to create a react component. The component can be created by using the useRef hook, which allows developers to store all the references to a DOM element. The next step is to create a dedicated component for any D3 visualization, like bar charts. So, within this set of components, try to use any React component to manage the D3 visualization logic.
Furthermore, as mentioned above, making use of the useEffect hooks, try to select the SVG element to set the dimensions, and this component also defines the scale and axes with the use of D3. Finally, integrate this D3 component into the main React component, passing in data as props. Additionally, by keeping all the D3 components, it is possible to manage all the updates easily and re-render them.
Strategy Points of D3 in the React JS Application
As we have seen from the above blog, when we blend D3JS with React, it has several other possibilities for creating all the dynamic and interactive data visualization, and by utilizing all of React’s component-based architecture and D3 data binding, most of the developers can build complex and more engaging visualizations with minimal code requirements. Additionally, this duo not only completely simplifies the development process but also boosts the customization of the data presentations. Additionally, if you are someone who is interested in advanced and innovative solutions with all the effective visualization solutions, then Pattem Digital, a leading ReactJS development company, is here to offer various innovative services that help businesses achieve their data visualization goals with D3JS and React.
0 notes
Text
Custom Hook useFocus() in react.jsc with Examples
The useFocus hook is a custom hook that makes an input element automatically get focused when a component is loaded. Here’s how you can do it:import { useEffect, useRef } from ‘react’; const useFocus = () => { const ref = useRef(null); useEffect(() => { if (ref.current) { ref.current.focus(); } }, []); return ref; }; […] The post Custom Hook useFocus() in react.jsc with Examples appeared first on TECH - WEB DEVELOPMENT NEWS. https://tech-webdevelopment.news-6.com/custom-hook-usefocus-in-react-jsc-with-examples/
0 notes
Text
How Do React Hooks Use the Push Method?
The push () method accepts an array and returns a new length after adding one or more members to the end of the array. The push method typically aids in adding the value to the array. It is a practical way to assign one or more key-value pairs to the object using bracket notation.
Using the push method makes assigning the value simple. These choices work well for adding the item to the array’s end. React hooks enable minimal code that may be used to quickly and easily create comparable features. These are good choices for using the lifecycle method in combination with the React state, even without using the writing class.If you need to integrate the Push method in your React apps then you need to hire React experts who will simply integrate this functionality in your app.
What are React Hooks?
React Hooks are a type of function that lets users connect function components to react state and lifecycle elements. UseState, useEffect, useReducer, useRef, use Callback, useContext, and useMemo are just a few of the built-in hooks that React offers. We can also design your own custom hooks.
As of React version 16.8, hooks for React are accessible. Before the introduction of hooks, only the class component—not the functional component—was able to preserve state. After the introduction of hooks, the functional component’s state can also be maintained.
Using all of React’s features, you may develop fully functional components by implementing the hooks concept. Unlike classes, this enables us to make everything simpler.
Advantages of React Hooks
Improving the Component Tree’s Readability
As it makes it possible to read context information outside of JSX, the “useContext” hook has been an invaluable tool for significantly increasing the readability of JSX. Although “useContext” makes it even cleaner, the static “contextType” assign in class components made this possible in the past.
Not only is the code easier to read, but using the React dev tools to debug makes it much simpler to read the component tree. This is really beneficial for components that were previously using many nested contexts.
Incorporating Adverse Effects
It was possible to add event listeners in “componentDidMount” and remove them later in “componentWillUnmount” for class components, which divided the setup and removal of side effects across several lifecycle methods. Any component with several side effects may result in code that is harder to read and has related functionality distributed over a number of disjointed lifecycle methods.
However, the “useEffect” handles side effect creation and breakdown, which fixes this issue. In order to accomplish this, it lets the effect function return a function that splits down the effect.
Acceptable and Reusable Logic
Undoubtedly, custom hooks are an excellent way to share functionality between different components. A custom hook is basically a function that, like a regular hook, can be called within a functional component and utilizes one or more React hooks.
Must You Include The Push Method?
The call() or apply()objects, which have a distinctive resemblance to arrays, are usually utilized in conjunction with the Push method. The push approach, in particular, depends on the length of the property, which makes it simple to choose which feature is best for beginning to insert values to a certain extent.
The index is set to 0 when the length property is not translated to a numerical value. In particular, it covers the potential for length with the nonexistent. In the process, length cases will be produced.
As strings are native, array-like objects are not appropriate choices for use in applications. These strings offer an appropriate solution to perfection and are unchangeable. Object parameters that resemble arrays are a good method for quickly figuring out the whole plan of action for excellence.
Hiring React js developers is a quick and hassle-free choice if you want to add the push function to your React hooks. React useState() hooks are required to update the array; they do not include the push() method for the Array object. In this process, the spread operator is a very practical choice.
push(element0)
push(element0, element1)
push(element0, element1, /* ... ,*/ elementN)
How Can I Use UseState() To Create An Array State?
The new length property of the object is included in the return value, which makes it easier to generate the Array state using useState(). To enable the array state variable, you must use the useState() hook.
import React from "react";
const { useState } = React;
const [myArray, setMyArray] = useState([]);
The variable containing the state array and the special technique for quickly updating each property are returned by the useState() hook. Without the useState() method, updating the array is typically very challenging.
It is quite convenient to add the new element to the State Array. It would be quite easy to add a new member to the array when this state is present.
myArray.push(1)
It’s a great option to use the best method return from useState while utilizing React to update the array with ease. Even with the new array that is formed by merging the old array with the new members in the JavaScript Spread operator, the update method, or setMyArray(), is useful for modifying the state. Using the useState update function makes it easy to create the new array from the old array.
setMyArray(oldArray => [...oldArray, newElement]);
It is convenient to utilize the first technique, and the function is enabled with the old array as the first parameter. Better access to older arrays containing state objects is also provided.
onChange = value => checked => {
this.setState({ checked }, () => {
this.setState(prevState => {
Object.assign(prevState.permission, { [value]: this.state.checked });
});
});
};
<CheckboxGroup
options={options}
value={checked}
onChange={this.onChange(this.props.label)}
/>
Adding The Array In React State Using Hooks
The.concat() function is useful for producing the speedy updating even without any problem, however the.push() function does not work well with updating the state in React app development. The spread operator makes it simple to enable JavaScript array state. In the React state, there are numerous methods for quickly adding an item to the array.
Pushing the item into the array is not a convenient choice because it is not quite as convenient to change the state directly. Using React Hooks to update state is made simple by the array’s React state. It’d be far more practical to store JavaScript objects with the array in React state.
1. The push() method adds new elements to the array’s end.
2. The push() method modifies the array’s length.
3. The push() function returns a new length.
For instance, useState is a hook that is enabled with functional components that make it simple to add additional functionality for the local state. React seems like a good choice for maintaining state in between renders.
The command useState([]) would automatically initialize the state to contain an empty array because these are known as the useState Hooks. The array is shown and is a suitable parameter for passing useState().
import React, { useState } from "react"
import ReactDOM from "react-dom"
function App() {
// React Hooks declarations
const [searches, setSearches] = useState([])
const [query, setQuery] = useState("")
const handleClick = () => {
// Save search term state to React Hooks
}
// ...
Pass a callback to the function that creates a new array in the state setter.
To add the new element to the end of the state array, we can pass in a callback that produces a new array. This would update the state array.
import React, { useState } from "react";
export default function App() {
const [arr, setArr] = useState(["Demo"]);
return (
<div classname="App">
<button onclick="{()" ==""> setArr((oldArray) => [...oldArray, "Demo"])}>
Click Here
</button>
<div>
{arr.map((a, i) => (
<p key="{i}">{a}</p>
))}
</div>
</div>
);
}
When using React Hooks, why does.Push() not work?
These are known as the reducers, and they are typically enabled by using the setSearches() major method. For updating the passed value’s current state, it is a handy alternative. TypeError, the search engine, is used to update these features with a number from an array. As the array’s method and state are enabled by .push, the state of [] replaces for the Map React state, and .length equals 1.
JavaScript does not apply code 1.map() when the.map() functioned.
The setSearches state setter or reducer function from React Hooks is a very practical way to update the state without altering the previous one. The rescue operation is taking place at Array. prototype.Concat() is a function that is used in push().
Reason.Concat() creates a new array in order to update the state. The old array would remain fully intact automatically. They would inevitably offer a higher return on the modified array.
setSearches([query].concat(searches)) // prepend to React State
To get the combined arrays quickly, you can use a JavaScript spread operator. In the React state, they are used to add the item to the array.
[...searches, query] to add a new entry to the array's end
To prepend an item to the front of the array, use [query,...searches].
// Save search term state to React Hooks with spread operator and wrapper function
// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))
// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))
// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])
// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])
Implement the State Setter Function
It is possible to give a callback into the state setter function that useState returns, which takes the old value of a state and produces a new one.
We only need to return a duplicate of the array in order to add the member we want to push to the end.
import { useState } from "react";
export default function App() {
const [arr, setArr] = useState([0]);
return (
<div><button> setArr((arr) => [...arr, arr[arr.length - 1] + 1])} > push </button> {JSON.stringify(arr)}</div>
); }
Conclusion
React component state arrays can be updated with new items at the end by sending a callback to the state setter function, which receives the old array value and returns the new and latest array value. As we saw above, we can modify the state of an array in React by using the Push function, specifically the useState hook. Incorporating new elements to JavaScript arrays is appropriate when using these methods. For integrating the React applications in the Push Method, you need to hire React Expert from a reputable React app development company in the USA.
Need More Information? Contact Us Today.
The React Company : Your Partner in React Excellence.
0 notes
Text
Title: Exploring Hooks: How to Supercharge Your React Components with Achieversit
Introduction: Since its introduction in React 16.8, hooks have revolutionized the way developers write React components, offering a more concise and intuitive way to manage state and side effects. In this guide, Achieversit takes you on a journey to explore the power of hooks and how they can supercharge your React components. Whether you're a beginner or an experienced React developer, mastering hooks is essential for building modern and efficient React applications.
Understanding Hooks: Achieversit starts by introducing the concept of hooks in React.js, explaining how they allow you to use state and other React features without writing class components. We'll explore the useState and useEffect hooks, discussing their syntax, usage, and common use cases.
Leveraging useState: The useState hook enables functional components to manage local state, eliminating the need for class components. Achieversit demonstrates how to use useState to initialize and update state variables, handle user input, and manage complex state logic within your React components.
Embracing useEffect: The useEffect hook provides a way to perform side effects in functional components, such as fetching data, subscribing to events, or updating the DOM. Achieversit dives deep into useEffect, exploring its various use cases, dependencies, cleanup mechanisms, and best practices for managing side effects in React components.
Custom Hooks: Custom hooks allow you to extract and reuse logic across multiple components, promoting code reusability and maintainability. Achieversit showcases how to create custom hooks to encapsulate complex logic, abstract common patterns, and share stateful logic between components effectively.
useContext Hook: The useContext hook provides a convenient way to consume context within functional components, enabling you to access global state or configuration settings without prop drilling. Achieversit demonstrates how to use useContext to access context values and update context state within your React components.
useRef Hook: The useRef hook allows you to create mutable references to DOM elements or values that persist across re-renders, without causing a component to re-render. Achieversit explores the useRef hook, showcasing its use cases for accessing DOM elements, managing focus, implementing timers, and optimizing performance in React components.
useMemo and useCallback Hooks: The useMemo and useCallback hooks are used to optimize performance by memoizing expensive computations and preventing unnecessary re-renders. Achieversit explains how to use useMemo and useCallback to optimize function components, improve rendering performance, and avoid unnecessary computations in React applications.
Conclusion: By mastering hooks, Achieversit empowers developers to write cleaner, more concise, and more maintainable React components. Whether you're building simple UI components or complex application logic, understanding how to leverage hooks effectively is essential for unlocking the full potential of React.js and building modern, high-performance web applications.
0 notes
Text
You can learn ReactJS easily, Here's all you need to get started:
1.Components
• Functional Components
• Class Components
• JSX (JavaScript XML) Syntax
2.Props (Properties)
• Passing Props
• Default Props
• Prop Types
3.State
• useState Hook
• Class Component State
• Immutable State
4.Lifecycle Methods (Class Components)
• componentDidMount
• componentDidUpdate
• componentWillUnmount
5.Hooks (Functional Components)
• useState
• useEffect
• useContext
• useReducer
• useCallback
• UseMemo
• UseRef
• uselmperativeHandle
• useLayoutEffect
6.Event Handling
• Handling Events in Functional Components
• Handling Events in Class Components
7.Conditional Rendering
• it Statements
• Ternary Operators
• Logical && Operator
8.Lists and Keys
• Rendering Lists
• Keys in React Lists
9.Component Composition
• Reusing Components
• Children Props
• Composition vs Inheritance
10.Higher-Order Components (HOC)
• Creating HOCs
• Using HOCs for Reusability
11.Render Props
• Using Render Props Pattern
12.React Router
• <BrowserRouter>
• <Route>
• <Link>
• <Switch>
• Route Parameters
13. Navigation
• useHistory Hook
• useLocation Hook
State Management
14.Context API
• Creating Context
• useContext Hook
15.Redux
• Actions
• Reducers
• Store
• connect Function (React-Redux)
16.Forms
• Handling Form Data
• Controlled Components
• Uncontrolled Components
17.Side Effects
• useEffect for Data Fetching
• useEffect Cleanup
18.AJAX Requests
• Fetch AP
• Axios Library
Error Handling
19.Error Boundaries
• componentDidCatch (Class Components)
• ErrorBoundary Component (Functional
Components)
20.Testing
• Jest Testing Framework
• React Testing Library
21. Best Practices
• Code Splitting
• PureComponent and React.memo
• Avoiding Reconciliation
• Keys for Dynamic Lists
22.Optimization
• Memoization
• Profiling and Performance Monitoring
23. Build and Deployment
• Create React App (CRA)
• Production Builds
• Deployment Strategies
Frameworks and Libraries
24.Styling Libraries
• Styled-components
• CSS Modules
25.State Management Libraries
• Redux
• MobX
26.Routing Libraries
• React Router
• Reach Router
0 notes
Text
The Road To NextJS + TypeScript.
Week 2
Aaaahhh.... back to writing again. So... as I am typing this, my most recent recording is being rendered for later publishing over on YouTube. YouTube, boy I should've started this channel years ago. But never-mind that.
(Audio issues: Now, in the first week I did a hard push in video recordings but only realized afterward that my audio was very off. Now, I'm re-working the audio on those previous vids so hang tight. If you see a video where I audio is too low, leave me a comment and I'll re-edit that video's audio.)
The past few weeks I've been pushing forward in on-line materials related to learning TypeScript. Some of the resources I've found helpful so far has been a video series from YouTuber Jack Herrington, a Lead engineer, his videos seem to be aimed at those folk that have been doing these crazy things for awhile and want to level up on the newer topics. I've found his content mostly illuminating when I can follow along, in those areas where I can't, I then go dive into the base level of the topic elsewhere, then circle back and revisit his video. Topics I've learned thus far include...
useContext
Redux Toolkit
Generics
Generic Components
Custom Hooks
useState and useEffect
useReducer and useRef
Tuples
Optionals
Function Overloading
Enums and Literal Types
Readonly and Immutability
Utility Types
And more... I won't list the entire thing here...that might be boring soooo check out my videos on youtube
I've got a few more to build out this week then I'll organize things into playlist(s). I'm hoping to work on Test Driven Development with TypeScript next. So we will see how things will go. After, finally, I'll revisit NextJS to apply there what I've learned here. Most likely I'll start with something very basic like how to build a basic single page and then how to do CRUD, then how to talk to a database. All the basic things, but in the context of NextJS. So the journey continues.
The YouTube page is a work in progress. I've dabbled in it off and on over time but I want to really build it up now, so hang on with me. I hope to build something that is useful to others. If you are reading this and if you're viewing me on YouTube.... thank you for stopping by.
OK, that's it for me now. See you in the next post.
1 note
·
View note
Text
React - useState - why setTimeout function does not have latest state value?
Recently I was working on React Hooks and got stuck with one problem/doubt?
Below is a basic implementation to reproduce the issue, Here I'm just toggling flag (a state) variable on click of the button.
const [flag, toggleFlag] = useState(false); const data = useRef(null); data.current = flag; const _onClick = () => { toggleFlag(!flag); // toggleFlag(!data.current); // working setTimeout(() => { toggleFlag(!flag); // does not have latest value, why ? // toggleFlag(!data.current); // working }, 2000); }; return ( <div className="App"> <button onClick={_onClick}>{flag ? "true" : "false"}</button> </div> );
I figured out some other way to overcome this problem like using useRef or useReducer, but is this correct or is there any other way to solve this with useState only?
Also, it would be really helpful if anyone explains why we get old value of state inside the setTimeout.
Sandbox URL - https://codesandbox.io/s/xp540ynomo
https://codehunter.cc/a/reactjs/react-usestate-why-settimeout-function-does-not-have-latest-state-value
0 notes
Text
Reactコンポネートーー制御か非制御か
こんにちは。mediba でテクノロジー2G にてFEをしております、楊です。
最近のPJ開発中にあったことで、Reactコンポネートの制御か非制御か当時綺麗に解決できなかったので、 振り返って、色々調べた上にまとめたメモです。
コンポネートの制御と非制御
React公式の説明
下手な絵で簡単に説明すると↓
ではどうすれば、非制御であり制御コンポネートでもあるコンポネートを作れるでしょう
最も簡単なやり方ーー内外のStateを持ちながら同期させる
まずは子コンポネート内でStateを持たせて、どんな状態(制御モード・非制御モード)でも自分のStateを使うようにする。 次は制御モードにおいて、内部StateをPropsと同期させれば、問題なさそう!
const Input: FC<{ value?: string; onChange?: (value: string) => void; }> = (props) => { const isControlled = props.value !== undefined; const [value, setValue] = useState(props.value); const handleOnChange = (e) => { if (isControlled) { setValue(e.target.value); props.onChange(e.target.value); } } useEffect(() => { if (isControlled) { setValue(props.value); } },[props.value]); return ( <input value={value} onChange={handleOnChange}/> ); };
よくみてみると、制御モードでは気になるところも出てきたね
子コンポネート内のState更新はParentより遅い
パフォマンス的によくない、useEffect内でのsetStateの使いなので、余計な再描画が発生してしまう
解決できそうかな、試してみよう
子コンポネート内のState更新はParentより遅い
これだと簡単に解決できそう、制御モードにおいてPropsから渡してきた値そのまま使えばいい。
const finalVal = isControlled ? props.value : value const handleOnChange = (e) => { if (isControlled) { setValue(e.target.value); props.onChange(e.target.value); } } return ( <input value={finalVal} onChange={handleOnChange}/> );
こうすれば、同期は一歩遅くても、子コンポネートに使ってもらうStateは必ず最新であることを担保できる。
パフォマンス的によくない、useEffect内でのsetStateの使いなので、余計なレンダリングが発生してしまう
useEffect内でのState同期なので、再描画を防げなくて、簡単なコンポネートであれば、パフォマンスの影響は少ないが、コンプレックスなコンポネートには、問題である
ポイントは同期させるタイミングだね、ならどうしよう、、、、
Stateでvalue保存には、setterで同期させた直後に再描画が始まる、もし再描画が制御可能になったら問題ないでしょう。 保存にはRefを使って、強制再描画には 仮のstateを作って
const [_, setObj] = useState({}) function triggerRendering(){ setObj({}) }
を使う。そうしたら全体は↓
const Input: FC<{ value?: string; onChange?: (value: string) => void; }> = (props) => { const isControlled = props.value !== undefined; const stateRef = useRef(props.value); if (isControlled) { stateRef.current = props.value; } const [_, setObj] = useState({}); function triggerRendering() { setObj({}); } const handleOnChange = (e: React.ChangeEvent) => { stateRef.current = e.target.value; triggerRendering(); props.onChange(e.target.value); }; return <input value={stateRef.current} onChange={handleOnChange}/>; };
こうしたことで値の同期による再描画がなくなり、制御同時に非制御のコンポネートが出来上がった。 refとhandleOnChangeの部分を取り出し、hooksにすることで、他のコンポネートに適用することもできるでしょう。
現在medibaではメンバーを大募集しています。
募集・応募ページ
medibaってどんな会社だろうと、興味を持っていただいた方は、カジュアル面談もやっておりますので、お気軽にお申込み頂ければと思います。
カジュアル面談
0 notes
Link
Live Stream: Feb 9, 2023 | Integrating OpenAI with a custom block. Part Two | WordPress Tutorial
0 notes
Text
tbh. I think that a less-complicated setup could probably work? just have each currently rendered post set its cell's height attribute in its inline style via useref, disconnect that resize observer when you unmount a post. don't use position:absolute. you are done now?
unless position:absolute is an important part of the benefit. (I guess I don't actually know what the point of this thing is in so many words so I can't really speculate further, now can I)
see also the problem is that like
the idea of doing a virtualized list render on elements with arbitrary heights that you don't know until you render them is fucking fascinating and has so many pitfalls and edge cases and space for performance optimizations. forget xkit—I want to play with* that source. this is one of the few problems I think I'd be uniquely good at solving, and I don't think those honestly come up in the real world very often.
*I was going to say see, and like, that too, but I kind of already figured a decent amount of it out already. that 100ms debounce seems clunky?
7 notes
·
View notes