Publish to my blog (weekly)

    • 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.
    • Normally, variables “disappear” when the function exits but state variables are preserved by React.
    • If we wanted to store two different values in state, we would call useState() twice.
    • State variables can hold objects and arrays just fine, so you can still group related data together. However, unlike this.setState in a class, updating a state variable always replaces it instead of merging it.
    • it doesn’t merge the old and new state together
    • stateful behavior
    • data fetching
    • manually changing the DOM
    • subscriptions
    • We call these operations “side effects” (or “effects” for short) because they can affect other components and can’t be done during rendering.
    • Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
    • Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions.
    • You can imagine that in a large app, this same pattern of subscribing to DataSource and calling setState will occur over and over again. We want an abstraction that allows us to define this logic in a single place and share it across many components. This is where higher-order components excel.
    • Hooks allow you to reuse stateful logic without changing your component hierarchy.
    • Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data)
    • rather than forcing a split based on lifecycle methods.
    • One such technique is the single responsibility principle, that is, a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.
    • If you’re familiar with the concept of state, don’t use state at all to build this static version
    • State is reserved only for interactivity, that is, data that changes over time.
    • it’s usually easier to go top-down, and on larger projects
    • it’s easier to go bottom-up and write tests as you build.
      • Is it passed in from a parent via props? If so, it probably isn’t state.
      •  
      • Does it remain unchanged over time? If so, it probably isn’t state.
      •  
      • Can you compute it based on any other state or props in your component? If so, it isn’t state.
      • Identify every component that renders something based on that state.
      •  
      • Find a common owner component (a single component above all the components that need the state in the hierarchy).
      •  
      • Either the common owner or another component higher up in the hierarchy should own the state.
      •  
      • If you can’t find a component where it makes sense to own the state, create a new component solely for holding the state and add it somewhere in the hierarchy above the common owner component.
    • We recommend that such components use the special children prop to pass children elements directly into their output:
    • {props.children}
    • <h1 className="Dialog-title"> Welcome </h1> <p className="Dialog-message"> Thank you for visiting our spacecraft! </p>
    • {props.left}
    • {props.right}
    • left={  <Contacts /> }
    • right={  <Chat /> } />
    • This approach may remind you of “slots” in other libraries but there are no limitations on what you can pass as props in React.
    • {props.children}
    • <input value={this.state.login} onChange={this.handleChange} /> <button onClick={this.handleSignUp}>
    • If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or class, without extending it.
    • const temperature = this.state.temperature;
    • In React, sharing state is accomplished by moving it up to the closest common ancestor of the components that need it. This is called “lifting state up”. We will remove the local state from the TemperatureInput and move it into the Calculator instead.
    • However, now that the temperature is coming from the parent as a prop, the TemperatureInput has no control over it.

       

      In React, this is usually solved by making a component “controlled”. Just like the DOM <input> accepts both a value and an onChange prop, so can the custom TemperatureInput accept both temperature and onTemperatureChange props from its parent Calculator.

    • this.props.onTemperatureChange(e.target.value);
    • const temperature = this.props.temperature;
    • this.state = {temperature: '', scale: 'c'};
    • const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature; const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
    • temperature={celsius} onTemperatureChange={this.handleCelsiusChange}
    • temperature={fahrenheit} onTemperatureChange={this.handleFahrenheitChange}
    • ref={(input) => (this._name = input)}
    • this.state = {  name: "",  };
    • this.setState({ name: event.target.value });
    • onChange={this.handleNameChange}
    • value={this.state.name}
    • This means your data (state) and UI (inputs) are always in sync.
    • input type="text"
    • .value
    • input type="checkbox"
    • .checked
    • input type="radio"
    • .checked
    • .value
    • textarea
    • .value
    • select
    • If your form is incredibly simple in terms of UI feedback, uncontrolled with refs is entirely fine.
    • this.input = React.createRef();
    • this.input.current.value
    • ref={this.input}
    • you can specify a defaultValue attribute instead of value. Changing the value of defaultValue attribute after a component has mounted will not cause any update of the value in the DOM.
    • defaultValue="Bob"
    • <input type="checkbox"> and <input type="radio"> support defaultChecked,
    • <select> and <textarea> supports defaultValue
    • this.fileInput = React.createRef();
    • this.fileInput.current.files[0].name
    • ref={this.fileInput}
    • onSubmit={this.handleSubmit}
    • onChange={this.handleChange}
    • value={this.state.value}
    • <textarea value={this.state.value} onChange={this.handleChange} />
    • <select value={this.state.value} onChange={this.handleChange}>
    • event.target.name.
    • const name = target.name;
    • this.setState({  [name]: value });
    • name="isGoing"
    • name="numberOfGuests"
    • this.handleLoginClick = this.handleLoginClick.bind(this);  this.handleLogoutClick = this.handleLogoutClick.bind(this);
    • const isLoggedIn = this.state.isLoggedIn;
    • if (isLoggedIn) {
    • {unreadMessages.length > 0 && <h2>
    • You have {unreadMessages.length} unread messages.
    • </h2>
    • if (!props.warn) { return null; }
    • Returning null from a component’s render method does not affect the firing of the component’s lifecycle methods. For instance componentDidUpdate will still be called.
    • InstanceField
    • StaticField
    • PublicInstanceMethod
    • React events are named using camelCase
    • With JSX you pass a function as the event handler, rather than a string.
    • You must call preventDefault explicitly
    • e.preventDefault();
    • // This binding is necessary to make `this` work in the callback this.handleClick = this.handleClick.bind(this);
    • onClick={this.handleClick}
    • if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.
    • If calling bind annoys you, there are two ways you can get around this. You can use public class fields syntax to correctly bind callbacks:
    • // This syntax ensures `this` is bound within handleClick. handleClick = () => { console.log('this is:', this); };
    • // This syntax ensures `this` is bound within handleClick
    • onClick={() => this.handleClick()}
    • The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering.
    • We generally recommend binding in the constructor or using the class fields syntax
    • with bind any further arguments are automatically forwarded.
    • State is similar to props, but it is private and fully controlled by the component.
    • Clock is now defined as a class rather than a function.
    • Class components should always call the base constructor with props.
    • ever
      • every time, 예외가 없다는 느낌. 매번 ~ 하는
    • The only place where you can assign this.state is the constructor.

       

    • Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
    • To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
    • stateful or stateless
    • This is commonly called a “top-down” or “unidirectional” data flow.
    • Any state is always owned by some specific component,
    • any data or UI derived from that state can only affect components “below” them in the tree.
    • We recommend naming props from the component’s own point of view rather than the context in which it is being used.
    • impure
    • All React components must act like pure functions with respect to their props.
    • All React components must act like pure functions with respect to their props.
    • All React components must act like pure functions with respect to their props.
    • Functions as Children
    • return <div>{items}</div>;
    • {(index) => <div key={index}>This is item {index} in the list</div>}
    • {showHeader && <Header />}
    • Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
    • We don’t recommend using indexes for keys if the order of items may change.
    • This can negatively impact performance and may cause issues with component state.
    • For example, if you extract a ListItem component, you should keep the key on the <ListItem /> elements in the array rather than on the <li> element in the ListItem itself.
    • // Correct! There is no need to specify the key here: return <li>{props.value}</li>;
    • // Correct! Key should be specified inside the array. <ListItem key={number.toString()} value={number} />
    • JSX allows embedding any expression in curly braces so we could inline the map() result:
    • {numbers.map((number) => <ListItem key={number.toString()} value={number} /> )}

Posted from Diigo. The rest of my favorite links are here.

댓글

이 블로그의 인기 게시물

Publish to my blog (weekly)

Publish to my blog (weekly)