concept initial state in category react

appears as: initial state, initial state, n initial state, The initial state
React Hooks in Action

This is an excerpt from Manning's book React Hooks in Action.

React only executes the function the first time the component’s rendered. It uses the function’s return value as the initial state.

When calling the useReducer hook, we pass it the reducer and an initial state. The hook returns the current state and a function for dispatching actions, as two elements in an array, as shown in figure 4.5.

Figure 4.5 Call useReducer with a reducer and an initial state. It returns the current state and a dispatch function. Use the dispatch function to dispatch actions to the reducer.

Although the example is simple, you should appreciate how a reducer can help structure your code, your state mutations and your understanding, particularly as the component state becomes more complex. If your state is complex and/or the initial state is expensive to set up or is generated by a function you’d like to reuse or import, the useReducer hook has a third argument you can use. Let’s check it out.

  • Call the useReducer hook when you want React to manage the state and reducer for a component. Pass it the reducer and an initial state. It returns an array with two elements: the state and a dispatch function.
  • const [ state, dispatch ] = useReducer( reducer, initialState );
  • Call the useReducer hook with an initialization argument and an initialization function to generate the initial state when the hook is first called. The hook automatically passes the initialization argument to the initialization function. The initialization function returns the initial state for the reducer. This is useful when initialization is expensive or when you want to use an existing function to initialize the state.
  • React in Action

    This is an excerpt from Manning's book React in Action.

    2.3.2. Setting initial state

    When should you use state and how do you get started using it? For now, the simple answer is when you want to make changes to data stored within a component. I said props were immutable (not modifiable), so if you need to change data, you need mutable state. In React, data that tends to need to be mutable often comes from or is the result of user input (often text, files, toggled options, and so on), but could be many other things. To keep track of user interactions with form elements, you need to provide an initial state and then change that state over time. You can use the constructor of the component to set the initial state for your component, a comment box component that builds on the ideas and concepts from earlier code listings. It will allow you to add comments to a post via a simple form. The following listing shows how to set up the component and set initial state.

    Listing 2.6. Setting initial state
    //... class CreateComment extends Component { constructor(props) { super(props); #1 this.state = { content: '', #1 user: '' #1 }; } render() { return React.createElement( 'form', { #2 className: 'createComment' }, React.createElement('input', { type: 'text', #2 placeholder: 'Your name', value: this.state.user }), React.createElement('input', { type: 'text', placeholder: 'Thoughts?' #2 }), React.createElement('input', { type: 'submit', value: 'Post' }) ); } } CreateComment.propTypes = { content: React.PropTypes.string }; //... const App = React.createElement( Post, { id: 1, content: ' said: This is a post!', user: 'mark' }, React.createElement(Comment, { id: 2, user: 'bob', content: ' commented: wow! how cool!' }), React.createElement(CreateComment) #3 ); #1 Call super in the class constructor and assign the initial state object to the instance of the class’s state property—note that you won’t normally assign state like this except in the constructor of the component class. #2 Create a component as a React class that will have some input fields for the user—I’ll cover forms in more detail in future chapters. #3 Add CreateComment to the App component. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":3,\"ch\":51},{\"line\":3,\"ch\":53}],[{\"line\":5,\"ch\":51},{\"line\":5,\"ch\":53}],[{\"line\":6,\"ch\":51},{\"line\":6,\"ch\":53}],[{\"line\":51,\"ch\":0},{\"line\":51,\"ch\":2}],[{\"line\":3,\"ch\":51},{\"line\":3,\"ch\":53}],[{\"line\":5,\"ch\":51},{\"line\":5,\"ch\":53}],[{\"line\":6,\"ch\":51},{\"line\":6,\"ch\":53}],[{\"line\":51,\"ch\":0},{\"line\":51,\"ch\":2}],[{\"line\":3,\"ch\":51},{\"line\":3,\"ch\":53}],[{\"line\":5,\"ch\":51},{\"line\":5,\"ch\":53}],[{\"line\":6,\"ch\":51},{\"line\":6,\"ch\":53}],[{\"line\":51,\"ch\":0},{\"line\":51,\"ch\":2}],[{\"line\":13,\"ch\":51},{\"line\":13,\"ch\":53}],[{\"line\":17,\"ch\":51},{\"line\":17,\"ch\":53}],[{\"line\":23,\"ch\":51},{\"line\":23,\"ch\":53}],[{\"line\":52,\"ch\":0},{\"line\":52,\"ch\":2}],[{\"line\":13,\"ch\":51},{\"line\":13,\"ch\":53}],[{\"line\":17,\"ch\":51},{\"line\":17,\"ch\":53}],[{\"line\":23,\"ch\":51},{\"line\":23,\"ch\":53}],[{\"line\":52,\"ch\":0},{\"line\":52,\"ch\":2}],[{\"line\":13,\"ch\":51},{\"line\":13,\"ch\":53}],[{\"line\":17,\"ch\":51},{\"line\":17,\"ch\":53}],[{\"line\":23,\"ch\":51},{\"line\":23,\"ch\":53}],[{\"line\":52,\"ch\":0},{\"line\":52,\"ch\":2}],[{\"line\":48,\"ch\":52},{\"line\":48,\"ch\":54}],[{\"line\":53,\"ch\":0},{\"line\":53,\"ch\":2}]]"} !@%STYLE%@!
    Listing 11.3. Creating the comments reducer (src/reducers/comments)
    import initialState from '../constants/initialState'; #1 import * as types from '../constants/types'; export function comments(state = initialState.comments, action) { #2 switch (action.type) { #3 case types.comments.GET: { #4 const { comments } = action; #4 let nextState = Object.assign({}, state); #4 for (let comment of comments) { if (!nextState[comment.id]) { nextState[comment.id] = comment; } } return nextState; #5 } case types.comments.CREATE: { #6 const { comment } = action; let nextState = Object.assign({}, state); nextState[comment.id] = comment; return nextState; } default: #7 return state; } } export function commentIds(state = initialState.commentIds, action) { switch (action.type) { case types.comments.GET: { const nextCommentIds = action.comments.map(comment => comment.id); #8 let nextState = Array.from(state); #9 for (let commentId of nextCommentIds) { if (!state.includes(commentId)) { nextState.push(commentId); } } return nextState; } case types.comments.CREATE: { #10 const { comment } = action; let nextState = Array.from(state); nextState.push(comment.id); return nextState; } default: return state; } } #1 Pull in initial state #2 Reducers are functions that take a state object and an action. #3 Use a switch statement to determine how to respond to incoming action #4 For GET, make copy of state and add comments you don’t already have #5 Return new state #6 Add new comment to state #7 By default return same state #8 You only want IDs here because you’ll store them separately from main objects. #9 Create copy of previous state #10 Push new ID in !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":72},{\"line\":0,\"ch\":74}],[{\"line\":38,\"ch\":71},{\"line\":38,\"ch\":73}],[{\"line\":49,\"ch\":0},{\"line\":49,\"ch\":2}],[{\"line\":58,\"ch\":0},{\"line\":58,\"ch\":2}],[{\"line\":2,\"ch\":72},{\"line\":2,\"ch\":74}],[{\"line\":50,\"ch\":0},{\"line\":50,\"ch\":2}],[{\"line\":3,\"ch\":72},{\"line\":3,\"ch\":74}],[{\"line\":51,\"ch\":0},{\"line\":51,\"ch\":2}],[{\"line\":4,\"ch\":72},{\"line\":4,\"ch\":74}],[{\"line\":5,\"ch\":72},{\"line\":5,\"ch\":74}],[{\"line\":6,\"ch\":72},{\"line\":6,\"ch\":74}],[{\"line\":52,\"ch\":0},{\"line\":52,\"ch\":2}],[{\"line\":4,\"ch\":72},{\"line\":4,\"ch\":74}],[{\"line\":5,\"ch\":72},{\"line\":5,\"ch\":74}],[{\"line\":6,\"ch\":72},{\"line\":6,\"ch\":74}],[{\"line\":52,\"ch\":0},{\"line\":52,\"ch\":2}],[{\"line\":4,\"ch\":72},{\"line\":4,\"ch\":74}],[{\"line\":5,\"ch\":72},{\"line\":5,\"ch\":74}],[{\"line\":6,\"ch\":72},{\"line\":6,\"ch\":74}],[{\"line\":52,\"ch\":0},{\"line\":52,\"ch\":2}],[{\"line\":12,\"ch\":71},{\"line\":12,\"ch\":73}],[{\"line\":53,\"ch\":0},{\"line\":53,\"ch\":2}],[{\"line\":14,\"ch\":71},{\"line\":14,\"ch\":73}],[{\"line\":54,\"ch\":0},{\"line\":54,\"ch\":2}],[{\"line\":20,\"ch\":71},{\"line\":20,\"ch\":73}],[{\"line\":55,\"ch\":0},{\"line\":55,\"ch\":2}],[{\"line\":29,\"ch\":71},{\"line\":29,\"ch\":73}],[{\"line\":56,\"ch\":0},{\"line\":56,\"ch\":2}],[{\"line\":30,\"ch\":71},{\"line\":30,\"ch\":73}],[{\"line\":57,\"ch\":0},{\"line\":57,\"ch\":2}],[{\"line\":38,\"ch\":71},{\"line\":38,\"ch\":74}],[{\"line\":58,\"ch\":0},{\"line\":58,\"ch\":3}]]"} !@%STYLE%@!

    You’ll create an initial state file that will help you determine your state shape and structure. In the constants folder, create a file named initialState.js. This will be the state of your Redux app before any actions have been dispatched or any changes have been made. You’ll include information for error and loading states, as well as some information about posts, comments, and the user. You’ll store the IDs for comments and posts in arrays and the main information for these in objects that you can easily reference. The following listing shows an example of setting up the initial state.

    React Quickly: Painless web apps with React, JSX, Redux, and GraphQL

    This is an excerpt from Manning's book React Quickly: Painless web apps with React, JSX, Redux, and GraphQL.

    4.2.2. Setting the initial state

    Thus far, you’ve seen that before you use state data in render(), you must initialize the state. To set the initial state, use this.state in the constructor with your ES6 class React.Component syntax. Don’t forget to invoke super() with properties; otherwise, the logic in the parent (React.Component) won’t work:

    class MyFancyComponent extends React.Component {
      constructor(props) {
        super(props)
        this.state = {...}
      }
      render() {
        ...
      }
    }

    You can also add other logic while you’re setting the initial state. For example, you can set the value of currentTime using new Date(). You can even use toLocaleString() to get the proper date and time format for the user’s location, as shown next (ch04/clock).